Skip to content Skip to sidebar Skip to footer

Using Pure Javascript Get The Element Visibility In Viewport In Percentage

I am trying to get the visibility of the element from viewport in percentage (number %). Below is the code which I tired, but something is missing. function calculateVisibilityForD

Solution 1:

I've modified few lines to work code and it's working fine. Check below fiddle

https://jsfiddle.net/darjiyogen/q16c1m7s/1/

'use strict';
var results = {};

functiondisplay() {
  var resultString = '';
  $.each(results, function(key) {
    resultString += '(' + key + ': ' + Math.round(results[key]) + '%)';
  });
  $('p').text(resultString);
}

functioncalculateVisibilityForDiv(div$) {
  debugger;
  div$ = div$[0];

  var windowHeight = window.innerHeight || document.documentElement.clientHeight,
    docScroll = window.scrollTop || document.body.scrollTop,
    divPosition = div$.offsetTop,
    divHeight = div$.offsetHeight || div$.clientHeight,
    hiddenBefore = docScroll - divPosition,
    hiddenAfter = (divPosition + divHeight) - (docScroll + windowHeight);

  if ((docScroll > divPosition + divHeight) || (divPosition > docScroll + windowHeight)) {
    return0;
  } else {
    var result = 100;

    if (hiddenBefore > 0) {
      result -= (hiddenBefore * 100) / divHeight;
    }

    if (hiddenAfter > 0) {
      result -= (hiddenAfter * 100) / divHeight;
    }

    return result;
  }
}

var getOffset = function(elem) {
  var box = {
    top: 0,
    left: 0
  };
  if (typeof elem.getBoundingClientRect !== "undefined") box = elem.getBoundingClientRect();
  return {
    x: box.left + (window.pageXOffset || document.scrollLeft || 0) - (document.clientLeft || 0),
    y: box.top + (window.pageYOffset || document.scrollTop || 0) - (document.clientTop || 0)
  };
};

functioncalculateAndDisplayForAllDivs() {
  $('div').each(function() {
    var div$ = $(this);
    results[div$.attr('id')] = calculateVisibilityForDiv(div$);
  });

  display();
}

$(document).scroll(function() {
  calculateAndDisplayForAllDivs();
});

$(document).ready(function() {
  calculateAndDisplayForAllDivs();
});
div {
  height: 300px;
  width: 300px;
  border-width: 1px;
  border-style: solid;
}

p {
  position: fixed;
  left: 320px;
  top: 4px;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><divid="div1">div1</div><divid="div2">div2</div><divid="div3">div3</div><divid="div4">div4</div><pid="result"></p>

Post a Comment for "Using Pure Javascript Get The Element Visibility In Viewport In Percentage"