Skip to content

Instantly share code, notes, and snippets.

@harryfinn
Created February 17, 2016 09:33
Show Gist options
  • Save harryfinn/75e0e3ea48987b7d0c0a to your computer and use it in GitHub Desktop.
Save harryfinn/75e0e3ea48987b7d0c0a to your computer and use it in GitHub Desktop.
isOnScreen jQuery plugin for check if given element is within the current viewport
(function($) {
$.fn.isOnScreen = function(x_offset, y_offset) {
if(x_offset == null || typeof x_offset == 'undefined') x_offset = 1;
if(y_offset == null || typeof y_offset == 'undefined') y_offset = 1;
var win = $(window),
viewport = {
top : win.scrollTop(),
left : win.scrollLeft()
},
height = this.outerHeight(),
width = this.outerWidth(),
bounds = this.offset(),
visible,
deltas;
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
if(!width || !height) return false;
bounds.right = bounds.left + width;
bounds.bottom = bounds.top + height;
visible = (
!(viewport.right < bounds.left ||
viewport.left > bounds.right ||
viewport.bottom < bounds.top ||
viewport.top > bounds.bottom)
);
if(!visible) return false;
deltas = {
top: Math.min(1, (bounds.bottom - viewport.top) / height),
bottom: Math.min(1, (viewport.bottom - bounds.top) / height),
left: Math.min(1, (bounds.right - viewport.left) / width),
right: Math.min(1, (viewport.right - bounds.left) / width)
};
return (deltas.left * deltas.right) >= x_offset && (deltas.top * deltas.bottom) >= y_offset;
};
})(jQuery);
@harryfinn
Copy link
Author

Usage

To use, simple call on the required element i.e.

if($('.contact-form').isOnScreen()) {
  // Display contact form/animate in/change user focus etc...
}

You can pass x & y offsets if you want the check to return true based on a percent/factor amount of the element on screen i.e. $('.contact-form').isOnScreen(0.2, 0.2) would return true if 20% of the element was visible on the x and y axises

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment