简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM