I've been trying to use a function to detect if an element is in the viewport:
function isElementInViewport (el) {
var rect = el[0].getBoundingClientRect();
return (rect.top>-1 && rect.bottom <= $(window).height());
}
var s= $('.special'),
y = $('.status');
$(window).on('scroll resize', function(){
if(isElementInViewport(s))
{
setTimeout(function(){
if(isElementInViewport(s))
{
var offer_id = s.data("offer-id");
alert(offer_id);
y.text('Yes');
}
}, 3000);
}
else
{
y.text('No');
}
});
Unfortunately this only seems to work for the first instance of the class 'special'. How do I get it to apply to all instances of that class?
Note that I've added a 3 second delay, to prevent fast scrolling from triggering it.
Here's the jsfiddle of my progress: http://jsfiddle.net/azjbrork/6/
using jquery each
we can run the function on each instance of the .special
class and report back accordingly (snippet below) :
function isElementInViewport(el) { var rect = el[0].getBoundingClientRect(); return (rect.top > -1 && rect.bottom <= $(window).height()); } var s = $('.special'), y = $('.status'); $(window).on('scroll resize', function() { s.each(function() { var $this = $(this); if (isElementInViewport($this)) { setTimeout(function() { if (isElementInViewport($this)) { var offer_id = $this.data("offer_id"); // advise using an underscore instead of a hyphen in data attributes // alert(offer_id); // reported in text below y.text('Yes : ' + offer_id); } }, 200); } else { // y.text('No'); // omit this line otherwise it will always report no (subsequent out of screen divs will overwrite the response) } }); });
.special { width: 80px; height: 20px; border: 1px solid #f90; margin-top: 200px; } .status { position: fixed; right: 2em; top: 1em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='special' data-offer_id='a'></div> <div class='special' data-offer_id='b'></div> <div class='special' data-offer_id='c'></div> <div class='special' data-offer_id='d'></div> <div class='special' data-offer_id='e'></div> <div class='special' data-offer_id='f'></div> <div class='status'></div>
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.