How much of an element is visible in viewport

check if element is in viewport
javascript check if element is visible on screen
vue-check if element is in viewport
check if element is in viewport react
isinviewport
javascript when element appears
jquery check if element is partially visible
viewport js

There's a div (brown rectangle) on the page. The page is higher than the viewport (orange rectangle) so it can be scrolled, which means that the div might only partially show up or not at all.

What's the simplest algorithm to tell how much % of the div is visible in the viewport?

(To make things easier, the div always fits into the viewport horizontally, so only the Y axis needs to be considered at the calculations.)

See one more example in fiddle: https://jsfiddle.net/1hfxom6h/3/

/*jslint browser: true*/
/*global jQuery, window, document*/
(function ($) {
    'use strict';
    var results = {};

    function display() {
        var resultString = '';

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

        $('p').text(resultString);
    }

    function calculateVisibilityForDiv(div$) {
        var windowHeight = $(window).height(),
            docScroll = $(document).scrollTop(),
            divPosition = div$.offset().top,
            divHeight = div$.height(),
            hiddenBefore = docScroll - divPosition,
            hiddenAfter = (divPosition + divHeight) - (docScroll + windowHeight);

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

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

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

            return result;
        }
    }

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

        display();
    }

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

    $(document).ready(function () {
        calculateAndDisplayForAllDivs();
    });
}(jQuery));
div {
    height:200px;
    width:300px;

    border-width:1px;
    border-style:solid;
}
p {
    position: fixed;
    left:320px;
    top:4px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>
<div id="div4">div4</div>
<p id="result"></p>

How to test if an element is in the viewport with vanilla JavaScript , If an element is in the viewport, it's position from the top and left will always be greater than or equal to 0 . It's distance from the right will be less than or equal to the total width of the viewport, and it's distance from the bottom will be less than or equal to the height of the viewport. Detect if an element is visible in the view port. Now why would any one in the right mind want to do that? Well you are reading this, so may be you know why. While all these exist, how many plugins…

Here's a snippet illustrating how you can calculate this.

I've put the % values in the boxes for readability, and it even kinda "follows" the viewport ^^ :

Fiddle version

function listVisibleBoxes() {

  var results = [];

  $("section").each(function () {

    var screenTop = document.documentElement.scrollTop;
    var screenBottom = document.documentElement.scrollTop + $(window).height();
    var boxTop = $(this).offset().top;
    var boxHeight = $(this).height();
    var boxBottom = boxTop + boxHeight;

    if(boxTop > screenTop) {
      if(boxBottom < screenBottom) {
        //full box
        results.push(this.id + "-100%");
        $(this).html("100%").css({ "line-height": "50vh" });
      } else if(boxTop < screenBottom) {
        //partial (bottom)
        var percent = Math.round((screenBottom - boxTop) / boxHeight * 100) + "%";
        var lineHeight = Math.round((screenBottom - boxTop) / boxHeight * 50) + "vh";
        results.push(this.id + "-" + percent);
        $(this).html(percent).css({ "line-height": lineHeight });
      }
    } else if(boxBottom > screenTop) {
      //partial (top)
      var percent = Math.round((boxBottom - screenTop) / boxHeight * 100) + "%";
      var lineHeight = 100 - Math.round((boxBottom - screenTop) / boxHeight * 50) + "vh";
      results.push(this.id + "-" + percent);
      $(this).html(percent).css({ "line-height": lineHeight });
    }
  });

  $("#data").html(results.join(" | "));

}

$(function () {

  listVisibleBoxes();

  $(window).on("scroll", function() {
    listVisibleBoxes();
  });

});
body {
  background-color: rgba(255, 191, 127, 1);
  font-family: Arial, sans-serif;
}

section {
  background-color: rgba(175, 153, 131, 1);
  height: 50vh;
  font-size: 5vh;
  line-height: 50vh;
  margin: 10vh auto;
  overflow: hidden;
  text-align: center;
  width: 50vw;
}

#data {
  background-color: rgba(255, 255, 255, .5);
  left: 0;
  padding: .5em;
  position: fixed;
  top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<section id="one"></section>
<section id="two"></section>
<section id="three"></section>
<section id="four"></section>
<section id="five"></section>
<section id="six"></section>

<div id="data">data here</div>

How to check if any part of an element is out of the viewport with , If most of the expanded menu is outside the viewport, you might want to handle that interaction differently. It doesn't matter if 10% of it is visible. // element is now visible in the viewport} else {// element has gone out of viewport}}); Here is jQuery InView git. isInViewport. isInViewport is another lightweight jQuery plugin to know if the element is in the viewable area. All you need is to add :in-viewport after the selector to trigger a function or do some action. Below is the code

After playing around a bit I think I've found perhaps the simplest way to do it: I basically determine how much the element extends over the viewport (doesn't matter in which direction) and based on this it can easily be calculated how much of it is visible.

// When the page is completely loaded.
$(document).ready(function() {

  // Returns in percentages how much can be seen vertically
  // of an element in the current viewport.
  $.fn.pvisible = function() {
    var eTop = this.offset().top;
    var eBottom = eTop + this.height();
    var wTop = $(window).scrollTop();
    var wBottom = wTop + $(window).height();
    var totalH = Math.max(eBottom, wBottom) - Math.min(eTop, wTop);
    var wComp = totalH - $(window).height();
    var eIn = this.height() - wComp;
    return (eIn <= 0 ? 0 : eIn / this.height() * 100);
  }

  // If the page is scrolled.
  $(window).scroll(function() {
    // Setting the opacity of the divs.
    $("div").each(function() {
      $(this).css("opacity", Math.round($(this).pvisible()) / 100);
    });
  });

});
html,
body {
  width: 100%;
  height: 100%;
}
body {
  background-color: rgba(255, 191, 127, 1);
}
div {
  width: 60%;
  height: 30%;
  margin: 5% auto;
  background-color: rgba(175, 153, 131, 1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>

Check If an Element is Visible in the Viewport in JavaScript, Checking if an element is visible in the viewport has many applications, for example: Perform lazy loading images. You only load the image if its container is visible  Determining if the element is in the viewport. If an element is in the viewport, it’s position from the top and left will always be greater than or equal to 0. It’s distance from the right will be less than or equal to the total width of the viewport, and it’s distance from the bottom will be less than or equal to the height of the viewport.

Chrome now supports Intersection Observer API: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

Example (TypeScript):

export const elementVisibleInPercent = (element: HTMLElement) => {
    return new Promise((resolve, reject) => {
        const observer = new IntersectionObserver((entries: IntersectionObserverEntry[]) => {
            entries.forEach((entry: IntersectionObserverEntry) => {
                resolve(Math.floor(entry.intersectionRatio * 100));
                clearTimeout(timeout);
                observer.disconnect();
            });
        });

        observer.observe(element);
        // Probably not needed, but in case something goes wrong.
        const timeout = setTimeout(() => {
            reject();
        }, 500);
    });
};

const example = document.getElementById('example');
const percentageVisible = elementVisibleInPercent(example);

Example (JavaScript):

export const elementVisibleInPercent = (element) => {
    return new Promise((resolve, reject) => {
        const observer = new IntersectionObserver(entries => {
            entries.forEach(entry => {
                resolve(Math.floor(entry.intersectionRatio * 100));
                clearTimeout(timeout);
                observer.disconnect();
            });
        });

        observer.observe(element);
        // Probably not needed, but in case something goes wrong.
        const timeout = setTimeout(() => {
            reject();
        }, 500);
    });
};

const example = document.getElementById('example');
const percentageVisible = elementVisibleInPercent(example);

JavaScript: Is element in viewport? · GitHub, http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible​-in-the-current-viewport. */. function Thank you very much! Copy link. In simpler terms, when any part of the element is between the top and bottom bounds of your viewport, the element is visible on your screen. Now you can write an if/else statement, where the if statement only runs when the above condition is met.

Detecting if an element is in the Viewport : jQuery, Detect if an element is visible in the view port. While all these exist, how many plugins… This forms the part of JS that concerns us most. When in paper space in AutoCAD, some or all elements shown in model space do not display within one or more viewports. A layer has VP Freeze turned on inside the viewport. The object is displayed the same color as the layout background. Using annotative objects, the scale of the viewport does not match that of the objects. 3D solids contained in block are not on Layer 0. Copy and Paste

jQuery Cookbook: Solutions & Examples for jQuery Developers, this solution, we know whether the top of the element is visible in the viewport; Alternatively, we could look at how much of the element is visible—if it is less  You can set any height and width on an iframe, but the whole document may not be visible. If you use viewport length units in your CSS within the iframe document, 1vh will be 1% of the height of the iframe, and 1vw will be 1% of the width of the document. iframe { width: 50vw; }

jQuery - Test if element is in viewport (Example), Test to determine if an element is visible within the viewport of the browser. My thanks and compliments to the original author. $.fn.isOnScreen  This doesn't seem to determine if the object is in the viewport, it simply detects if the the element has been scrolled past. i.e. it returns true even if the element is at the bottom of the page (out of the viewport), and your viewport is at the top, and only returns false once the element leaves the top of the viewport.

Comments
  • Many else ifs with scrollTop and /scrollBottom (scrollTop+element.height): Two different cases for 0%s, one case when it's fully visible, and two other different cases if it's partially visible top and bottom. Many ifs, and then many calculations inside these blocks, and it feels super redundant. So it seemed too complicated, then I got the idea that the whole thing is axially symmetric from the middle of the viewport, the calculations deliver the same values just with different signs, so I thought there should be a simpler, more universal way doing it (abs?) than many ifs, that's why I asked.
  • 3 ifs, not much more : ) just store as much values as you can instead of making jQuery calls all the time. Both answers quite illustrate this.
  • console.log is not very convenient to see the info : )
  • Thank you very much for useful snippet, time saver really @Stanislav
  • The problem I have with this is that when the element is higher than the window height, it says for example it's 30% in viewport. That is correct in some way. But the logic I would like to see is that it calls that 100% in viewport. So even if it's a part of a element but it covers the full height of the screen, it should be 100% in viewport. How would I implement that in this script?