How to get on-screen visible element objects in jQuery? [duplicate]
Solution 1:
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 ]
Step 1:
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>
.
Step 2:
Initialise function on scroll
event:
$(window).bind("scroll", function() {
//your code placeholder
});
.
Step 3:
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');
});
Step 4:
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/