Check a DOM element is visible on screen or not using jQuery

When the DOM elements are loaded not all the elements are visible on screen/viewport. Using JavaScript/jQuery we can very easily detect that the element is visible on screen or not.

One of the use cases of element is visible

On my website I had ads and not all the ads were visible on  screen as soon as the  page loads. I needed to detect when the element is visible on screen per user scroll. 

I wrote a boolean function with the help of this post to return true if the element is visible on the screen. The function will return false if the element is not visible on the screen. The function is added to the jQuery object so that it can be used with any standard jQuery DOM element object. 

Snippet of element is visible function

$.fn.isElementVisibleOnScreen = function () {
     var elementTop = $(this).offset().top,
        elementBottom = $(this).offset().top + $(this).outerHeight(),
        screenTop = $(window).scrollTop(),
        screenBottom = $(window).scrollTop() + window.innerHeight;
     return ((screenBottom > elementTop) && (screenTop < elementBottom)) ? true : false;    
  }

Usuage of the above element is visible funciton

Assuming you have an element with the class called 'element'. We can simply call the above method as follows: 

console.log($('.element').isElementVisibleOnScreen());


Comments