Skip to content Skip to sidebar Skip to footer

Javascript/jquery Add Class When Element Comes Into Viewport?

Is there a way to add a class when the element that I want to apply the class to comes into the viewport? Or when the bottom of the screen is a certain distance past the top of the

Solution 1:

You could do something like this: (See CodePen for implementation)

Function taken from here: Check if element is visible after scrolling

CodePen

$(window).on('scroll', function() {
  $(".graph").each(function() {
    if (isScrolledIntoView($(this))) {
      $(this).find(".graph-line").addClass("graph-75");
      $(this).find(".graph-line-2").addClass("opacity");
    }
  });
});

functionisScrolledIntoView(elem) {
  var docViewTop = $(window).scrollTop();
  var docViewBottom = docViewTop + $(window).height();

  var elemTop = $(elem).offset().top;
  var elemBottom = elemTop + $(elem).height();

  return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

Altough this is not perfect, it should point you into the right direction.

Solution 2:

You're on the right track, I think if you use the scroll event with a function such as the answer to this similar question:

Check if element is visible after scrolling

Hope that helps :)

Post a Comment for "Javascript/jquery Add Class When Element Comes Into Viewport?"