JQuery: use the .toggle () alternative which is deprecated

I have images with the class name ".mute_btn", and when I click on them, the image source changes:

$('.mute_btn').toggle(function () { var clicked = false; var src = $(this).attr("src"); src = src.replace(/(.*)\.(png|gif|jpg|jpeg)$/, "$1-over.$2"); $(this).attr("src", src); }, function () { var src = $(this).attr("src"); src = src.replace(/(.*)-over\.(png|gif|jpg|jpeg)$/, "$1.$2"); $(this).attr("src", src); }); 

But I saw toggle () deprecated in jQuery 1.8

So I'm trying to do it like this:

 var clicked = false; $('.mute_btn').click(function() { if (clicked) { var src = $(this).attr("src"); src = src.replace(/(.*)-over\.(png|gif|jpg|jpeg)$/, "$1.$2"); $(this).attr("src", src); clicked = false; } else { var src = $(this).attr("src"); src = src.replace(/(.*)\.(png|gif|jpg|jpeg)$/, "$1-over.$2"); $(this).attr("src", src); clicked = true; }}); 

But the result is not perfect. Once upon a time, images do not change.

Do you know what is wrong?

+4
source share
4 answers

Live demo

 $('.mute_btn').click(function () { var src = this.src; var isClicked = src.indexOf('-over') > -1 ; // true if '-over' is found if( isClicked ){ this.src = src.replace(/(.*)-over\.(png|gif|jpg|jpeg)$/, "$1.$2"); }else{ this.src = src.replace(/(.*)\.(png|gif|jpg|jpeg)$/, "$1-over.$2"); } }); 

LIVE DEMO using ternary operator

 $('.mute_btn').click(function () { var src = this.src; var isClicked = src.indexOf('-over') > -1 ; this.src = isClicked ? src.replace(/(.*)-over\.(png|gif|jpg|jpeg)$/, "$1.$2") : src.replace(/(.*)\.(png|gif|jpg|jpeg)$/, "$1-over.$2") ; }); 
+3
source

I suspect the problem is that you have multiple images, but you are trying to control your click status with a single variable. Try to save the click state of individual items as follows:

 $('.mute_btn').click(function() { if ($(this).data("clicked")) { var src = $(this).attr("src"); src = src.replace(/(.*)-over\.(png|gif|jpg|jpeg)$/, "$1.$2"); $(this).attr("src", src); $(this).data("clicked",false); } else { var src = $(this).attr("src"); src = src.replace(/(.*)\.(png|gif|jpg|jpeg)$/, "$1-over.$2"); $(this).attr("src", src); $(this).data("clicked",true); } }); 

Please note that you can cache your $(this) object instead of creating a new one each time, but I did not do this so that the changes needed to solve your problem are more obvious.

+4
source

Use MIGRATE code available from jQuery

Take a look here to learn more about this: Equivalent to jQuery Toggle deprecated event

+2
source

The code I'm using is:

 $('#example').click(function() { isClicked=$(this).data('clicked'); if (isClicked) {isClicked=false;} else {isClicked=true;} $(this).data('clicked',isClicked); if(isClicked) { ...do stuff... } else { ...do stuff... } }); 
+1
source

All Articles