1

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');
        }
      });
    });

2 Answers 2

2

Here is for you :

$(window).on('resize scroll', function() {
  var found = false;
  $('.swapbg-dark').each(function() {
    found = found || $(this).isInViewport();
  });
  if (found) {
    $('body').addClass('dark-theme');
  } else {
    $('body').removeClass('dark-theme');
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Would it make more sense to use .filter instead of .each and an external variable?
0

As say @SpoonMeiser , you can do this too :

$(window).on('resize scroll', function() {
  var found = $('.swapbg-dark').filter(function() {
      return $(this).isInViewport();
    }).length !== 0;
  if (found) {
    $('body').addClass('dark-theme');
  } else {
    $('body').removeClass('dark-theme');
  }
});

1 Comment

You can even remove the found variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.