Answer: Use the jQuery :visible Selector You can use the jQuery :visible selector to check whether an element is visible in the layout or not. This selector will also select the elements with visibility: hidden; or opacity: 0; , because they preserve space in the layout even they are not visible to the eye.
Summary. Use the getBoundingClientRect() method to get the size of the element and its relative position to the viewport. Compare the position of the element with the viewport height and width to check if the element is visible in the viewport or not.
The :visible selector in jQuery is used to select every element which is currently visible. It works upon the visible elements. The elements that are consuming space in the document are considered visible elements. The height and width of visible elements are larger than 0.
To know whether the element is fully visible in viewport, you will need to check whether top >= 0, and bottom is less than the screen height. In a similar way you can also check for partial visibility, top is less than screen height and bottom >= 0. The Javascript code could be written as : window.
First of all on-screen visible area
is known as Viewport
.
(image is taken from OP. Cleared and edited in Photoshop)
So all you need is to detect all elements in your Viewport
.
This can be achieved using many plugins for jQuery, but I'll explain you on one example, which is called as jQuery withinviewport
Link to source and documentation on: [ withInViewport - Github ]
Download plugins and include jQuery
framework and withinviewport
plugin in your script:
<script src="http://code.jquery.com/jquery-1.7.min.js"></script>
<script src="withinViewport.js"></script>
<script src="jquery.withinviewport.js"></script>
.
Initialise function on scroll
event:
$(window).bind("scroll", function() {
//your code placeholder
});
.
Use withinviewport
selector to get all elements in you Viewport and by each element add class to corresponding list-item in your #timeline
container:
$("#elements > div").withinviewport().each(function() {
$('#timeline > li[view-id="'+$(this)[0].id+'"]').addClass('active');
});
Put all together:
$(window).bind("scroll", function() {
//clear all active class
$('#timeline > li').removeClass('active');
//add active class to timeline
$("#elements > div").withinviewport().each(function() {
$('#timeline > li[view-id="'+$(this)[0].id+'"]').addClass('active');
});
});
.
.
Also this plugin gives you opportunity to set top, bottom, left and right offset for view-port.
See demo here: http://patik.com/code/within-viewport/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With