Calculate percentage of a specific element has been scrolled into visible on the screen


HTML
<div class='info-container flex-layout'>
  <span>Scroll down</span>
  <span class='percent'>0%</span>
</div>
<div class='block'></div>
<div class='element flex-layout'>
  <span>Start</span>
  <span>End</span>
</div>
<div class='block'></div>

CSS
body {
  margin: 0;
  padding: 0;
  color: white;
}
.flex-layout {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.info-container {
  position: fixed;
  z-index: 1;
  font-size: 2em;
  height: 100%;
  width: 100%;
  align-items: flex-end;
  color: white;
}
.block {
  height: 1000px;
  background: #333;
}
.element {
  align-items: center;
  background: #000;
  height: 450px;
}
JavaScript
$(document).ready(function() {
  $(window).scroll(function() {
    var windowBottom = $(this).scrollTop() + $(this).height();
    var elementTop = $(".element").offset().top;
    var percentage = (windowBottom - elementTop) / $(".element").height() * 100;

    if (percentage >= 100) {
      $(".percent").text('100%');
    } else if (windowBottom >= elementTop) {
      $(".percent").text(`${Math.round(percentage)}%`);
    } else {
      $(".percent").text('0%');
    }
  });
});

Demo

Comments

Popular posts from this blog

HTML5 video loop src change on end play function

Custom OpenCart 2.3.0.2 theme

PHP: Date Difference for PHP 5.2