By Protonet Team. Published 29. December 2010.
A couple of months ago, we needed a way to detect whether an element is visible to the user. The use case behind this was that we wanted to implement an endless scrolling mechanism for the Protonet dashboard timeline: If the user reaches the last message in the timeline more messages had to be loaded without the user clicking anywhere. You might have seen such thing in the new twitter web site.
Thanks to Google, we stumbled upon this blog post written by Remy Sharp. There he shows off something that was exactly what we were searching for: A bindable event for jQuery which gets triggered as soon as the element appears in the browser’s viewport. The plugin was very suitable in the beginning.
Luckily someone already brought the code to GitHub. Starting a hardcore forking action and implementing and fixing the above mentioned issues was the obvious thing to do.
The plugin is compatible with the following browsers we tested:
$("#foobar").bind("inview", function(isVisible) {
// Event is triggered once the element becomes visible in the browser's viewport, and once when it becomes invisible
if (isVisible) {
console.log("element #foobar became visible in the browser's viewport");
} else {
console.log("element #foobar became invisible in the browser's viewport");
}
});
Wait to load images until they appear in the viewport.
$('img[data-src]').live('inview', function(event, isVisible) {
if (!isVisible) { return; }
var img = $(this);
img
.css('opacity', 0)
// Show a smooth animation when the image is loaded
.load(function() { img.animate({ opacity: 1 }, 500); })
// Change src
.attr('src', img.attr('data-src'))
// Remove it from matching set of elements of live event selector
.removeAttr('data-src');
});
Protonet’s Experimental Platform Is Here