Categories : JQuery

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

Check if element is visible in viewport using jquery library in javascript :

Ready to Use FULL Code

function detect_visibility(){
    
    var top_of_element = $(".element").offset().top;
    var bottom_of_element = $(".element").offset().top + $(".element").outerHeight();
    var bottom_of_screen = $(window).scrollTop() + $(window).innerHeight();
    var top_of_screen = $(window).scrollTop();

    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
    } else {
        // the element is not visible, do something else
    }

}

// detect when element gets visible on scroll
$(window).scroll(function() {
    detect_visibility();
});

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

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.

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

Element Top Offset

var top_of_element = $(".element").offset().top;

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").offset().top + $(".element").outerHeight();

In this line of code we get bottom offset of element

Window Bottom Offset and Top Offset

var bottom_of_screen = $(window).scrollTop() + $(window).innerHeight();
var top_of_screen = $(window).scrollTop();

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
} else {
   // the element is not visible, do something else
}

2 responses to “JQuery detect when element is visible on screen – viewport”

  1. Geekix says:

    Hello,

    This is exactly what I was looking for, it works great with the latest JQuery library version (3.6.0 as I write this).

    Thanks a lot !!

    • admin says:

      I am glad to hear that it helped you. Thank you for your comment my friend. That was my first comment in my website.

Leave a Reply

Your email address will not be published.