Determine Element Visibility Percentage In jQuery - percentWithinViewport
File Size: | 4.78 KB |
---|---|
Views Total: | 1809 |
Last Update: | |
Publish Date: | |
Official Website: | Go to website |
License: | MIT |
percentWithinViewport is a lightweight jQuery plugin that calculates the visibility of matched element (as a percentage) on scroll and determines if the element is visible in the viewport.
How to use it:
1. Download and place the minified version of the jQuery percentWithinViewport plugin after jQuery library.
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha384-tsQFqpEReu7ZLhBV2VZlAu7zcOV+rXbYlF2cqB8txI/8aZajjp4Bqd+V6D5IgvKT" crossorigin="anonymous"> </script> <script src="jquery.vnm.percentWithinViewport.min.js"></script>
2. Call the function and specify the elements you want to track the visibility in the viewport.
<div class="element"> Element 1 </div> <div class="element"> Element 2 </div> <div class="element"> Element 3 </div>
$('.element').percentWithinViewport();
3. This will insert the visibility percentage into the data-percent-viewport
as follows:
<div class="element" data-percent-viewport="10"> Element 1 </div> <div class="element" data-percent-viewport="100"> Element 2 </div> <div class="element" data-percent-viewport="50"> Element 3 </div>
4. You can also specify the top/bottom offsets & offset elements in the JavaScript as follows.
$('.element').percentWithinViewport({ offsetTop: 0, offsetTopElement: false, offsetBottom: 0, offsetBottomElement: false });
5. Advanced usaage. This will return array of elements that are within the viewport and do something as you scroll down/up the webpage.
$(window).on('scroll', function(e) { var withinViewportArray = $('.element').percentWithinViewport(); $.each(withinViewportArray, function(index) { // do something }); })
This awesome jQuery plugin is developed by indextwo. For more Advanced Usages, please check the demo page or visit the official website.