Skip to content

Instantly share code, notes, and snippets.

@aliang
Created August 1, 2010 08:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aliang/503107 to your computer and use it in GitHub Desktop.
Save aliang/503107 to your computer and use it in GitHub Desktop.
methods for seeing if something is in the viewport. see also http://github.com/xing/prototype-within-viewport
Element.Methods.centerIsWithinViewport = function(element) {
var dim = document.viewport.getDimensions();
var so = document.viewport.getScrollOffsets();
var co = element.cumulativeOffset();
var edim = element.getDimensions();
// x and y measured from upper left
var center = {
x: co.left + (edim.width / 2),
y: co.top + (edim.height / 2)
}
return (center.x > so.left &&
center.x < so.left + dim.width &&
center.y > so.top &&
center.y < so.top + dim.height);
};
Element.Methods.isWithinViewport = function(element) {
var dim = document.viewport.getDimensions();
var so = document.viewport.getScrollOffsets();
var co = element.cumulativeOffset();
var edim = element.getDimensions();
// there exists one corner within the viewport
var ul = { x: co.left, y: co.top };
var ur = { x: co.left + edim.width, y: co.top };
var ll = { x: co.left, y: co.top + edim.height };
var lr = { x: co.left + edim.width, y: co.top + edim.height };
return (ul.x > so.left &&
ul.x < so.left + dim.width &&
ul.y > so.top &&
ul.y < so.top + dim.height) ||
(ur.x > so.left &&
ur.x < so.left + dim.width &&
ur.y > so.top &&
ur.y < so.top + dim.height) ||
(ll.x > so.left &&
ll.x < so.left + dim.width &&
ll.y > so.top &&
ll.y < so.top + dim.height) ||
(lr.x > so.left &&
lr.x < so.left + dim.width &&
lr.y > so.top &&
lr.y < so.top + dim.height);
}
Element.addMethods();
// then use a periodical executer to see if they scroll it into view
// now you know
document.observe("dom:loaded", function() {
var e = $('test');
new PeriodicalExecuter(function(pe) {
if (e.centerIsWithinViewport()) {
pe.stop();
alert('made it in view')
// log it so we know people are at least seeing the message
}
}, 3);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment