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

質問

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

役に立ちましたか?

解決

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top