Skip to content

Instantly share code, notes, and snippets.

@jayllellis
Created January 21, 2015 14:12
Show Gist options
  • Save jayllellis/64b114732e7fa080c0fa to your computer and use it in GitHub Desktop.
Save jayllellis/64b114732e7fa080c0fa to your computer and use it in GitHub Desktop.
Top of element becomes visible within viewport
/**
* @desc checks if current element is on screen or within viewport (as soon as it becomes visible)
* @param none
* @return int - the coordinates of the window vs. the element
*/
jQuery.fn.isOnScreen = function(){
var win = $(window);
var viewport = {
top : win.scrollTop(), //top of screen
left : win.scrollLeft()//left of screen
};
viewport.right = viewport.left + win.width();//total width starting from left of screen
viewport.bottom = viewport.top + win.height();//total height starting from top of screen
var elemtTop = this.height() / 1.1;// Get the height of the element and divide by 1.1
var elemtHeight = this.height() - elemtTop;// Subtract the previous value from total height ( = basically the top)
elemtHeight = Math.round(elemtHeight);// Round it to whole humber
var bounds = this.offset();// Coordinates of current element
bounds.top = bounds.top + elemtHeight;// The instant the element is visible
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();
return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
}
// Usage:
$(document).ready(function(){
if( $('.before_footer_wrapper').isOnScreen() ){// If '.before_footer_wrapper' becomes visible
$('#back_to_top').css('position', 'absolute');// Make button sit on top of '.before_footer_wrapper'
}
else{// If '.before_footer_wrapper' goes offscreen
$('#back_to_top').css('position', '');// Make button fixed so it follows the user as they scroll
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment