Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform function in attr() callback?

Not sure if I am doing this correctly 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 am trying to do is Set a IMG Opacity to 0 (#swapImg), replace it's src, then fade it back in. So I am trying to fade it back in using a callback from the .attr().

If I am doing this incorrectly, can someone please explain a better way to do this? The reason I am trying to do it in the callback is that I need the fadeTo to only occur after the new image is fully loaded, otherwise it does a bit of a flash.

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

like image 791
Jared Avatar asked Mar 12 '10 20:03

Jared


People also ask

What is callback () in JavaScript?

A JavaScript callback is a function which is to be executed after another function has finished execution. A more formal definition would be - Any function that is passed as an argument to another function so that it can be executed in that other function is called as a callback function.

How do you write a callback function?

A custom callback function can be created by using the callback keyword as the last parameter. It can then be invoked by calling the callback() function at the end of the function. The typeof operator is optionally used to check if the argument passed is actually a function. console.

What is callback function example?

Example: Using a Callback FunctionThe sayName() function is passed as an argument to the greet() function. The setTimeout() method executes the greet() function only after 2 seconds. However, the sayName() function waits for the execution of the greet() function.

When callback function is executed?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. The above example is a synchronous callback, as it is executed immediately.


1 Answers

You can do this with the load event like this:

$("#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");
             });

The fade will start after the image load event fires.

like image 76
Nick Craver Avatar answered Oct 04 '22 04:10

Nick Craver