I have a script that notifies the console log whenever a given div is in the browser window, it is not pretty, but here it is:
$(window).bind('scroll', function(){
var $canvas = $('div#example');
var pos = $canvas.offset();
var total = pos.top + $($canvas).height();
var wndtop = $(this).scrollTop();
if(wndtop <= pos || wndtop >= total ){
console.log("off screen")
}
if(wndtop >= pos || wndtop <= total ){
console.log("on screen")
}
});
This script works fine if the #div is at the top of the page, but if it is not at the top of the page, it will always return “on screen”. How could I modify this so that it would return the correct info no matter where the div is on the page?
http://www.jsfiddle.net/Q7T3b/
I guess I thought this would be a cool little exercise.
Normally I would extend the Native Number object with some sort of method like withinRange(low,high);
But this seems to be working… Although it’s in no way tested beyond “Looks good enough”; && it’s dirty. So don’t tell anyone I did it.
When you’re running functionality on an intensive event such as “Scroll” or “Mousemove”, you need to be sure what ever is running in there is as nimble as possible. DOM Queries are anything BUT fast, and they come with a large overhead. I recommend avoiding queries on such events.