I am using the below code to add a class on a selected element when scrolled into the view-port.
HTML below:
<?php
$counter=1;
while ( have_posts() ) : the_post(); ?>
<div id="archiveItem-<?php echo $counter; ?>" class="mydiv floatLeft">
<a href="<?php the_permalink();?>">
<img src="placement.jpg" alt="">
<h3><?php the_title(); ?></h3>
</a>
</div>
<?php
$counter++;
endwhile; ?>
function isScrolledIntoView(elem) {
if (!jQuery(elem).length) return false;
var docViewTop = jQuery(window).scrollTop();
var docViewBottom = docViewTop + jQuery(window).height();
var elemTop = jQuery(elem).offset().top;
var elemBottom = elemTop + jQuery(elem).height();
return ((elemTop <= docViewBottom) && (elemBottom >= docViewTop));
}
jQuery(window).scroll(function () {
jQuery('.mydiv').each(function () {
if (isScrolledIntoView(this)) {
jQuery(this).addClass('divshow');
}
});
});
It works fine but I would like to only add a class to divs that are not in the viewport. It currently adds the class to all divs until scrolled into view.
See example below:
From the screenshot the first two rows of divs (1-10) should not have the class added as they are in view but the below divs (15-20) are out of view and should have the class added when scrolled into view.
Any help appreciated
Thanks
using below code you can check if a div is in view or not and apply classes accordingly