I have a simple jQuery click handler that animates the change of a divs background image. I would like to create some reusable code so I would not have to copy my code for every div I would like this effect on. How would I go about this?

<style type="text/css">

#divtest.toggled {
	background-image: url('images/alert_closed_small.gif');
	background-position: center;
	background-repeat: repeat;
	background-color:silver;
}
.nottoggled {
	background-image: url('images/alert_future_small.gif');
	background-position: center;
	background-repeat: repeat;
	background-color:silver;
	
}

<script type="text/javascript">

$(document).ready(function(){
  
var toggle=0;

$("#divtest").click(function(event){  

if (toggle == 0) {
		$("#divtest").slideUp("slow", function(){
		$("#divtest").addClass("toggled"); 
		});  
		$("#divtest").slideDown("slow", function() {  
		toggle=1;
                });  

                }else if(toggle == 1) {

		$("#divtest").slideUp("slow", function(){
		$("#divtest").removeClass("toggled");
		$("#divtest").addClass("nottoggled"); 
		});  
		$("#divtest").slideDown("slow", function() {  
	     	toggle=0;
		});  
  }
});

Mapper,

You can avoid the need for the toggle flag by testing whether class name "toggled" is set or not. This makes life much easier.

Also, in jQuery you can address many elements with one statement by giving them all the same class. Here I assume the class name "myTogglingClass", (which you will replace with something more suitable).

Untested

$(document).ready(function(){
  $(".myTogglingClass").click(function(){
    var $this = $(this);
    $this.slideUp("slow", function(){
      if($this.hasClass('toggled')) {
        $this.removeClass("toggled");
        $this.addClass("nottoggled");
      } else {
        $this.removeClass("nottoggled");
        $this.addClass("toggled");
      }
      $this.slideDown("slow");  
    });
  });
});

With a little more thought, it could become even simpler.

Airshow

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.