Skip to content

Instantly share code, notes, and snippets.

@ben-heath
Created August 1, 2016 15:59
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 ben-heath/303e244f981c67576ac6774c2c297f1a to your computer and use it in GitHub Desktop.
Save ben-heath/303e244f981c67576ac6774c2c297f1a to your computer and use it in GitHub Desktop.
Run code when a specific html element is visible on a page
var $findit = jQuery('#visualisation'); // element that needs to be in view for thing to happen
function Scrolledit() {
$findit.each(function() {
var $section = jQuery(this),
finditOffset = $section.offset(),
finditTop = finditOffset.top,
finditBottom = $section.height() + finditTop,
scrollTop = jQuery(document).scrollTop(),
visibleBottom = window.innerHeight,
prevVisible = $section.prop('_visible');
if ((finditTop > scrollTop + visibleBottom) ||
finditBottom < scrollTop) {
visible = false;
} else visible = true;
if (!prevVisible && visible) {
animate_path(); // this is where the code goes that you want to happen when the element is visible
}
$section.prop('_visible', visible);
});
}
function Setupit() {
var $top = jQuery('#top'),
$bottom = jQuery('#bottom');
$top.height(500);
$bottom.height(500);
jQuery(window).scroll(function() {
Scrolledit();
});
}
jQuery(document).ready(function() {
Setupit();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment