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

StackOverflow https://stackoverflow.com/questions/22913305

Domanda

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

È stato utile?

Soluzione

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top