peter
peter

Reputation: 71

Add a class on scrolling before 20% of the element

I have this function and it's executed on scrolling to the element and it becomes in view , I want to edit it to execute on scrolling before 20% of the element.

JS:

function isScrolledIntoView(elem) {
  var centerY = Math.max(0, ((jQuery(window).height() - jQuery(elem).outerHeight()) / 2) +
    jQuery(window).scrollTop());
  var elementTop = jQuery(elem).offset().top;
  var elementBottom = elementTop + jQuery(elem).height();
  return elementTop <= centerY && elementBottom >= centerY;
}

jQuery(window).on("scroll resize", function() {
  jQuery(".element)").each(function(index, element) {
    if (isScrolledIntoView(element)) {
      jQuery(element).addClass("newClass");
    }
  });
});

HTML:

<div class='element'>New Class Will Be Added Before 20% Of This Div</div>

Upvotes: 0

Views: 60

Answers (1)

Bhuwan
Bhuwan

Reputation: 16855

You have to calculate the 20% of the element height and then subtract it from the element offset from top using $(this).offset().top

Stack Snippet

jQuery(window).on("scroll resize", function() {
  jQuery(".element").each(function() {
    var percentage = ($(this).outerHeight() * 20) / 100;
    if (jQuery(window).scrollTop() > jQuery(this).offset().top - percentage) {
      jQuery(this).addClass("newClass");
    } else {
      jQuery(this).removeClass("newClass");
    }
  });
});
.element {
  height: 200px;
  width: 200px;
  background: red;
  color: #fff;
  margin: 0 auto 30px;
}

body {
  margin: 300px 0;
}

.element.newClass {
  background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='element'>New Class Will Be Added Before 20% Of This Div</div>
<div class='element'>New Class Will Be Added Before 20% Of This Div</div>
<div class='element'>New Class Will Be Added Before 20% Of This Div</div>
<div class='element'>New Class Will Be Added Before 20% Of This Div</div>
<div class='element'>New Class Will Be Added Before 20% Of This Div</div>

Upvotes: 2

Related Questions