Detect If An Element Is Visible - jQuery onScreen
| File Size: | 7.31 KB |
|---|---|
| Views Total: | 2182 |
| Last Update: | |
| Publish Date: | |
| Official Website: | Go to website |
| License: | MIT |
This inView checker plugin provides a collection of useful event handlers to do some cool stuff when an element or only part of the element becomes visible (or invisible) on page scroll.
Basic usage:
1. Add the JavaScript file jquery.onscreen.js after jQuery library and the onScreen plugin is ready for use.
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin="anonymous">
</script>
<script src="jquery.onscreen.js"></script>
2. Check an element's state using the Inview event. Possible parameters:
- visiblePartX: horizontal part of the element (left, right, both, none).
- visiblePartY: vertical part of the element (top, bottom, both, none).
$('.box').on('inview', function(event, isInView, visiblePartX, visiblePartY) {
if (isInView) {
alert('element is now visible in the viewport!');
if (visiblePartY == 'top') {
alert('top part of element is visible!')
} else if (visiblePartY == 'bottom') {
alert('bottom part of element is visible!')
} else {
alert('whole part of element is visible!');
}
} else {
alert('element has gone out of viewport!');
}
});
3. Check an element's state using the onscreen event that will keep firing if the user scrolls and the element remains on screen or not. Possible parameters:
- top: top offset
- left: left offset
- bottom: bottom offset
- right: right offset
- percentFromTop: Percentage offset of top
- percentFromLeft: Percentage offset of left
- percentFromBottom: Percentage offset of bottom
- percentFromRight: Percentage offset of right
- percentInview: Percentage area inview compared to the total possible inview area
- percentInviewHorizontal: Percentage horizonally inview compared to the total possible inview horizonally
- percentInviewVertical: Percentage vertically inview compared to the total possible inview vertically
- onscreen: True/ or false
- uniqueMeasurementId: Unique measurement Id
$('div').on('onscreen', function(event, measurement) {
if (measurement.percentInview > 0) {
alert('element is now visible in the viewport');
if (measurement.percentInviewVertical < 50) {
alert('element is less than half onscreen vertically');
} else {
alert('element is half or more than half onscreen vertically');
}
} else {
alert('element has gone out of viewport');
}
});
4. Decide whether to allow scroll over.
$.inview.config({
allowScrollOver: false
});
Change log:
2018-01-23
- drop ie8 support
This awesome jQuery plugin is developed by adaptlearning. For more Advanced Usages, please check the demo page or visit the official website.











