I am trying to add a class to the body of my page whenever an element called .swapbg-dark comes into the viewport.
Here is my current code. I have managed to make it work for one of the elements, but when it scrolls past the second it does not retrigger and then removes the class.
JSfiddle here: https://jsfiddle.net/4xpwaq2g/
$.fn.isInViewport = function() {
var elementTop = $(this).offset().top + 300;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
$(window).on('resize scroll', function() {
$('.swapbg-dark').each(function() {
if ($('.swapbg-dark').isInViewport()) {
$('body').addClass('dark-theme');
} else {
$('body').removeClass('dark-theme');
}
});
});