简体   繁体   中英

How to check if the user scrolled to 30% of an element, from the top or the bottom

As specified in the title, I'm listening to scroll event in order to fire a function when 30% of a video shows up in the window - regardless whether the user scrolls up or down.

What is have is this:

// On DOM ready, I set the top and bottom offset of the video,
// +/- 30% of the video height

var $video = $('#js-b2b-video');
var videoHeight = $video.outerHeight();
var videoHeight30 = parseInt(videoHeight/3, 10); // Approx. 30% of the video height
var videoObj = {}

videoObj.top = $video.offset().top + videoHeight30; // Approx. 30% from the top of the video
videoObj.bottom = videoObj.top + videoHeight - videoHeight30; // Approx. 30% from the bottom of the video

Then, the scroll event:

$(window).on('scroll', function() {
    if ($(window).scrollTop() >= videoObj.top) {
        alert('30% from the top of the video reached');
    }
});

However, this fires too late, when the video is fully visible. What I need is to fire my function immediately when 30% of the top or bottom of the video is visible.

How do I do this properly?

Fiddle

您需要考虑窗口高度。

if ($(window).scrollTop() + $(window).height() >= videoObj.top) {

You probably need to consider the window height as well:

if ($(window).scrollTop() + window.innerHeight >= videoObj.top) {

Note that you might want to test on onload and resize too...

Try it

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