Recent Posts
- (09/10) Fixing Warning: the ECDSA host key for 'github.com' differs from the key for the IP addressTAGS:Web Server Admin
- (12/26) CakePHP 3 - Getting List of Column Definitions from a Table (like schema())TAGS:CakephpCake3
- (09/14) Change Order of Loaded Behaviors in CakePHP 3TAGS:Cake3CakephpWeb ProgrammingPhp
- (05/29) CakePHP 3 - Accept JSON Header Only Working When Debug FalseTAGS:Web ProgrammingCakephpCake3
- (05/23) Remove All Events from Google Calendar (Reset Calendar)TAGS:Web ProgrammingPhp
- (11/08) Google Tag Manager (GTM) Not Firing Default PageView EventTAGS:Web ProgrammingJavascriptGoogle Tag Manager
- (10/13) In PHP, how do you get __toString() Magic Method Result without calling echo?TAGS:CakephpCake3Cakephp 13PhpWeb Programming
- (11/14) Getting output from shell_exec() at all timesTAGS:Web ProgrammingWeb Server Admin
Subscribe to my feed
MainelyDesign.com Blog
jQuery: Checking If An Object Is Visible On The Screen
Posted on 09/12/2014 at 12:03 pm by Kevin Wentworth
Viewed 10,919 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:
- $.fn.isVisible = function() {
- // Current distance from the top of the page
- var windowScrollTopView = $(window).scrollTop();
- // Current distance from the top of the page, plus the height of the window
- var windowBottomView = windowScrollTopView + $(window).height();
- // Element distance from top
- var elemTop = $(this).offset().top;
- // Element distance from top, plus the height of the element
- var elemBottom = elemTop + $(this).height();
- return ((elemBottom <= windowBottomView) && (elemTop >= windowScrollTopView));
- }
How To Use It:
- $(document).ready(function() {
- $(window).scroll(function() {
- if($("#header").isVisible()) {
- $("body").addClass('atTop');
- } else {
- $("body").removeClass('atTop');
- }
- });
- });
With the option to check for element visibility, a developer should be able to take the "responsive design" idea to a whole new level.
Minified:
- $.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
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!