Bart Bussel
Bart Bussel

Reputation: 176

jquery on scroll event

I am trying to make it so a img changes to a gif when the user is scrolling on a site.

HTML

<img src="img/giphy.gif" alt="" id="imgAnimate">

JQUERY

$(document).ready(function()
        {
            $("#imgAnimate").hover(
                function()
                {
                    $(this).attr("src", "img/giphy.gif");
                },
                function()
                {
                    $(this).attr("src", "img/giphy.png");
                });
        });

I got this but now is it when you hover over the img it changes into a gif. How can I make this happen when user is scrolling.

Thanks you if you can help me.

Upvotes: 1

Views: 5756

Answers (3)

Ahmed Salama
Ahmed Salama

Reputation: 2825

https://jsfiddle.net/q6Lun0dj/1/

use this script :

(function( $ ) {
  $(function() {
    var scrollNow = false;
    $( window ).scroll(function() {
      if(!scrollNow){
        scrollNow = true;
        $("#imgAnimate").attr("src", "http://bart.aoweb.nl/template%205/img/giphy.gif");
      }
      clearTimeout( $.data( this, "scrollCheck" ) );
      $.data( this, "scrollCheck", setTimeout(function() {
        scrollNow = false;
        $("#imgAnimate").attr("src", "http://bart.aoweb.nl/template%205/img/giphy.png");
      }, 250) );

    });

  });

})( jQuery );

Upvotes: 1

user2278730
user2278730

Reputation: 31

When you scroll, you can use this code

  $(document).ready(function(){
       $( window ).scroll(function(){
                $(this).attr("src", "img/giphy.gif");
            });
    });

when you stop scrolling you can Event when user stops scrolling

Upvotes: 1

GMchris
GMchris

Reputation: 5658

Currently you're checking if the image is being hovered and only then changing it's source. Instead attach a scroll event listener to the document.

$(document).on('scroll', callback);

Upvotes: 0

Related Questions