Created
February 17, 2016 09:33
-
-
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
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
(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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
To use, simple call on the required element i.e.
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 thex
andy
axises