I personally would just use the JavaScript code to switch between 2 classes.
Have the CSS outline everything you need on your div MINUS the background rule, then add two classes (e.g: expanded & collapsed) as rules each with the correct background image (or background position if using a sprite).
CSS with different images
.div { /* button size etc properties */ } .expanded {background: url(img/x.gif) no-repeat left top;} .collapsed {background: url(img/y.gif) no-repeat left top;}
Or CSS with image sprite
.div { background: url(img/sprite.gif) no-repeat left top; /* Other styles */ } .expanded {background-position: left bottom;}
Then...
JavaScript code with images
$(function){ $('#button').click(function(){ if($(this).hasClass('expanded')) { $(this).addClass('collapsed').removeClass('expanded'); } else { $(this).addClass('expanded').removeClass('collapsed'); } }); }
JavaScript with sprite
Note: the elegant toggleClass does not work in Internet Explorer 6, but the below addClass/removeClass method will work fine in this situation as well
The most elegant solution (unfortunately not Internet Explorer 6 friendly)
$(function){ $('#button').click(function(){ $(this).toggleClass('expanded'); }); } $(function){ $('#button').click(function(){ if($(this).hasClass('expanded')) { $(this).removeClass('expanded'); } else { $(this).addClass('expanded'); } }); }
As far as I know this method will work accross browsers, and I would feel much more comfortable playing with CSS and classes than with URL changes in the script.
Aug 9 '10 at 0:42at SO maybe that's why, :(