I have a + icon and a - icon. When someone clicks the + icon a box appears and the icon changes to a - icon. If they click again the box disappears and the icon changes to a + icon.
Here is the code I tried but its not working...
$("#box").toggle(function(e){
$("#icon").attr ("src","/images/icon开发者_StackOverflow_expand.png")
},
function(e) {
$("#icon").attr("src","/images/icon_retract.png")
}
);
Any ideas?
Thank you!
The .toggle()
function attaches click
handlers to the element, not event handlers for then an element is toggled visible, it should be attached to #icon
, like this:
$("#icon").toggle(function(){
$("#box").hide();
this.src = "/images/icon_expand.png";
}, function() {
$("#box").show();
this.src = "/images/icon_retract.png";
});
$.togle () toggles the visibility of the matched element(s). So you are using it completely wrong.
You'll have to do something like this:
$( '#icon' ).click ( function () {
var $this = $( this );
var $box = $( '#box' );
$box.toggle ();
if ( $box.is ( ':visible' ) === true ) {
$this.attr ( "src", "/images/icon_retract.png" );
} else {
$this.attr ( "src", "/images/icon_expand.png" );
}
} );
i think, there will be a correction in Nick code and then it will work fine.
you have to first show the box and on second click you have to hide it, if is it so,
then try this
$("#icon").toggle(function(){
$("#box").show();
this.src = "/images/icon_expand.png";
}, function() {
$("#box").hide();
this.src = "/images/icon_retract.png";
});
精彩评论