I'm trying to write a function so that when my element comes into view a function is attached to it.
I have a range of elements on my page, element1, element2, element3 and I'd like to write a function that checks when either of these is in the viewport, rather than having a big if statement.
I have the following only this doesn't seem to work, and nothing happens?
var $findme = $('.section').each();
function Scrolled() {
var findmeOffset = $findme.offset(),
findmeTop = findmeOffset.top,
scrollTop = $(document).scrollTop(),
visibleBottom = window.innerHeight;
if (findmeTop < scrollTop + visibleBottom) {
console.log('element is visible');
}
}
function Setup() {
var $top = $('#top'),
$bottom = $('#bottom');
$top.height(500);
$bottom.height(500);
$(window).scroll(function() {
Scrolled();
});
}
$(document).ready(function() {
Setup();
});
DEMO
I think the problem is related to your declaration of $findme. You're passing an array of HTML elements, but in Scrolled() you're looking for one specific top offset.
The demo you provided will work if you pass an id of one specific element rather than the class identifier of all elements.
Maybe you could update the code above to pass one identifier at a time to Scrolled(). I'm not sure how to accomplish this in the context of your application, sorry.