Execute function in attr () callback?

Not sure if I am doing it right or not.

Here is my .js :

 var currentIMG; $( '.leftMenuProductButton' ).hover(function () { currentIMG = $("#swapImg").attr("src"); var swapIMG = $(this).next(".menuPopup").attr("id"); $("#swapImg").css("opacity", 0) .attr("src", productImages[swapIMG], function(){ $("#swapImg").fadeTo("slow", 1); }); }, function () { $("#swapImg").stop().attr("src",currentIMG); }); 

What I'm trying to do is set the opacity of the IMG to 0 ( #swapImg ), replace it with src , and then bring it back. So I'm trying to get it back using a callback from .attr() .

If I do it wrong, can someone explain the best way to do this? The reason I'm trying to do this in a callback is because I need fadeTo to appear only after the new image is fully loaded, otherwise it flashes a bit.

I am using jQuery 1.4, and according to http://jquery14.com/day-01/jquery-14 you can make a callback in the .attr() method.

+4
source share
2 answers

You can do this using the load event as follows:

 $("#swapImg").css("opacity", 0).attr("src", productImages[swapIMG]) .one("load",function(){ //fires (only once) when loaded $(this).fadeIn("slow"); }).each(function(){ if(this.complete) //trigger load if cached in certain browsers $(this).trigger("load"); }); 

Attenuation will begin after the image upload event is triggered.

+7
source
 $("#swapImg").css("opacity", 0).attr("src", productImages[swapIMG]) .on("load",function(){ //fires each time when image loaded $(this).fadeIn("slow"); }); 

This will also be correct.

0
source

Source: https://habr.com/ru/post/1303974/


All Articles