Categories : Javascript

what we made in this code ? Line by line js code?

How to Check if element is visible in viewport using javascript library in javascript and add scroll event to detect when element is in screen:

Video and new version of this writing is here : https://gokhancelebi.net/how-to-detect-when-element-is-visible-on-screen-with-javascript/

Ready to Use FULL Code

// detect when element gets visible on scroll
    window.addEventListener("scroll", detect_visibility);

    // detect when screen opens for first time
    detect_visibility();

    function detect_visibility() {

        var element = document.getElementById("element");

        var top_of_element = element.offsetTop;
        var bottom_of_element = element.offsetTop + element.offsetHeight + element.style.marginTop;
        var bottom_of_screen = window.scrollY + window.innerHeight;
        var top_of_screen = window.scrollY;

        if ((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)) {
            // Element is visible write your codes here
            // You can add animation or other codes here
            alert("element is visible")
        } else {
            // the element is not visible, do something else
            alert("element is not visible")
        }

    }

detect_visibility ()

With this function i wrote you above you can detect if element inside secreen viewport. It calculates based on offset and element height. You can use this to implement lazyload or animations.

If you want to check if div is visible on screen use “getElemgetElementsByClassName()” or “getElementById” for div class or id

You can add animaton classes in the // Element is visible section of detect_visibility function

Element Top Offset

   var top_of_element = element.offsetTop;

In this line of code we get offset of element that we want to know if it is visibile.

Element Bottom Offset

var bottom_of_element = element.offsetTop + element.offsetHeight + element.style.marginTop;

In this line of code we get bottom offset of element

Window Bottom Offset and Top Offset

var bottom_of_screen = window.scrollY + window.innerHeight;
var top_of_screen = window.scrollY;

In the first line we get window screen’s bottom offset

In the second line we get windows screen’s top offset

Final : Calculate to detect if element is visible and shown on screen of user

if ((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)) {
      // Element is visible write your codes here
      // You can add animation or other codes here
      alert("element is visible")
} else {
      // the element is not visible, do something else
      alert("element is not visible")
 }

Leave a Reply

Your email address will not be published. Required fields are marked *