Created
September 7, 2011 07:52
-
-
Save bolmaster2/1199999 to your computer and use it in GitHub Desktop.
Is element in view? A cross-browser way to check if a specific element is in viewport
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// check if el is in view | |
function is_el_in_view(el, full_el_visible) { | |
if (!el) return false; | |
// should we return true if the element is only partially visible (default) | |
full_el_visible = typeof full_el_visible != "undefined" ? full_el_visible : false; | |
var el_pos = get_absolute_offset(el), | |
el_h = el.offsetHeight, | |
window_h = window.innerHeight || document.documentElement.clientHeight, | |
viewport_y = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop, | |
viewport_bottom_y = viewport_y + window_h, | |
el_pos_bottom = el_pos + el_h; | |
if ( (viewport_bottom_y >= el_pos && viewport_y <= el_pos) // is the element top between the viewport range (top and bottom) | |
|| (viewport_bottom_y >= el_pos_bottom && viewport_y <= el_pos_bottom) // is the element bottom between the viewport range (top and bottom) | |
|| (viewport_y >= el_pos && viewport_bottom_y <= el_pos_bottom)) { // is the element bigger than the viewport? | |
// ok, we can see the element, at least part of it. we should check if the whole element is visible | |
if (full_el_visible) { | |
if ( (el_pos <= viewport_bottom_y && el_pos_bottom > viewport_bottom_y) // partially visible in bottom | |
|| (el_pos <= viewport_y && el_pos_bottom > viewport_y)) { // partially visible in top | |
// only partially visible, return false | |
return false; | |
} else { | |
// full visible element! | |
return true; | |
} | |
} else { | |
return true; | |
} | |
} else { | |
return false; | |
} | |
function get_absolute_offset(el) { | |
var offset = 0; | |
while (el != null) { | |
offset += el.offsetTop; | |
el = el.offsetParent; | |
} | |
return offset; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment