jQuery: Checking If An Object Is Visible On The Screen

Posted on 09/12/2014 at 12:03 pm by Kevin Wentworth
Viewed 10,656 times | 0 comments

In the ether known as the internet, people have been going from a static built and styled website, to much more responsive and interactive designs. Knowing this, I felt that it was important to be able to check if an element is currently displayed on the screen.

What Is This Useful For?

Currently, being able to detect if an element is visible on the screen can yield very promising options for development. Whether you need to check if a popup is already there, or want to be able to detect how far down the page someone is, this works perfectly for it.

The Plugin:

  1. $.fn.isVisible = function() {
  2.     // Current distance from the top of the page
  3.     var windowScrollTopView = $(window).scrollTop();
  5.     // Current distance from the top of the page, plus the height of the window
  6.     var windowBottomView = windowScrollTopView + $(window).height();
  8.     // Element distance from top
  9.     var elemTop = $(this).offset().top;
  11.     // Element distance from top, plus the height of the element
  12.     var elemBottom = elemTop + $(this).height();
  14.     return ((elemBottom <= windowBottomView) && (elemTop >= windowScrollTopView));
  15. }

How To Use It:

  1. $(document).ready(function() {
  2.     $(window).scroll(function() {
  3.         if($("#header").isVisible()) {
  4.             $("body").addClass('atTop');
  5.         } else {
  6.             $("body").removeClass('atTop');
  7.         }
  8.     });
  9. });

With the option to check for element visibility, a developer should be able to take the "responsive design" idea to a whole new level.


  1. $.fn.isVisible=function(){var e=$(window).scrollTop();var t=e+$(window).height();var n=$(this).offset().top;var r=n+$(this).height();return r<=t&&n>=e}

Good luck, Fellow Programmers

Bookmark and Share

Tags for jQuery: Checking If An Object Is Visible On The Screen

Jquery | Web Programming | Responsive

Comments for this Posting

No comments. Be the first to post a reply.

Sorry, comments are closed for this posting.

Please Email Kevin if you have any questions. Thanks!

Meet Site Avenger - Hosted Content Management System

Powered By: Site Avenger | Site Production: Saco Design