jQuery image PULSE animation on mouseover, fades to another image

921 views Asked by At

I'm trying to make an effect where on mouseover the image pulses between two different files in jQuery. I have the beginning written, but I'm struggling with the actual animation part.

Here is what I have so far. I know that I need to write something that tells the image to fade into the next image and then fades back. Thanks in advance for your time.

(function($) {
    $(document).ready(function() {
        window.pulse_image = null;
        window.pulse_continue_loop = false;

        $('.pulse').mouseover(function() {
            // User is hovering over the image.
            window.pulse_continue_loop = true;
            window.pulse_image = $(this);

            PulseAnimation(); // start the loop     
        }).mouseout(function() {
            window.pulse_continue_loop = false;
            window.pulse_image.stop();
        });
    });
})(jQuery);

I'm hoping to do something similar to this where it would be easy to apply to multiple images - having two images, one example_off.jpg and example_on.jpg.

jQuery(function(){
            $(".img-swap").hover(
                function(){this.src = this.src.replace("_off","_on");},
                function(){this.src = this.src.replace("_on","_off");
            });
        });
1

There are 1 answers

1
Jason On

Well, you don't necessarily need a plugin to do this. Lets say you have an image tag like

<img id = "image" src = "/path/to/front_image" data-alternate = "/path/to/back_image" width = "50" height = "50" />

You can set the data attribute to hold the path to the alternate image, and implement a swap like

//bind mouse events to image element with a given function
$("img#image").on("mouseover", function(e){
                imageSwap($(e.currentTarget));  
               })
               .on("mouseout", function(e){                 
                 imageSwap($(e.currentTarget));
               });

function imageSwap(image){
   //get the alternate source image as a placeholder
   var newSource = image.data("alternate"); 

   //save the image's current source in the data attribute
   image.data("alternate", image.attr("src"));

   //execute fadeOut operation of the image
   image.fadeOut("fast", function(e){

     //replace the image source attribute with the new image source
     image.attr("src") = newSource;

     //execute the fadeIn operation to show the new image
     image.fadeIn("fast");
   }); 
}

What this allows you to do is bind the mouseover and mouseout events to a single function that swaps the image source attributes with a data variable and executes a fadeOut and fadeIn operation in sequence.