Search code examples
javascriptjqueryscrolltoponscroll

How to trigger event after i scroll a page certain amount in pixels from the top? Javascript or Jquery


I am trying to trigger a video when I scroll a page 300px from the top. This works if I scroll

window.onscroll = function(event) {
myvideo.play();
}

but I would like it to play once I scroll 300px


Solution

  • You can check $(document).scrollTop()

    Try:

     $(document).bind("scroll", function(){    
        if ($(document).scrollTop() >= 300) {
           myvideo.play();
        }
    });
    

    EDIT

    Because We dont want the movie to play every time they scroll a pixel beyond 300 after the video is played you can unbind the event

    $(document).bind("scroll.myScroll", function(){    
        if ($(document).scrollTop() >= 300) {
            myvideo.play();
            $(document).unbind('.myScroll');
        }
    });
    

    DEMO