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
Here is a woking solution: jsfiddle.
Your main problem is that you were using
$fimdme
in youscroll
event handler, what caused that it only applied to the first element. Calling.each()
to an element with no arguments has no effect at all.Here's the new code. I modified it so, every time you scroll, the alert shows the text of a section if, and only if, it is visible now (in the viewport) and was not visible before, whether you scroll down or you scroll up.