Detect Most Visible Elements With jQuery - most-visible

Detect Most Visible Elements With jQuery - most-visible
File Size: 50.9 KB
Views Total:
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

most-visible is a lightweight jQuery plugin that detects the most visible element within the document. It also provides an option that allows you to decide whether to calculate visibility as a percentage of the element's height.

Installation:

# Yarn
$ yarn add most-visible

# NPM
$ npm install most-visible --save

How to use it:

1. Import the jQuery most-visible.

// ES 6
import MostVisible from 'most-visible';

// CommonJS:
const MostVisible = require('most-visible');

2. Or Load the JavaScript file most-visible.js after the latest jQuery JavaScript library (slim build).

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" 
        integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" 
        crossorigin="anonymous">
</script>
<script src="most-visible.js"></script>

3. The JavaScript to detect which content section is the most visible within the document and then add a custom CSS class to it.

<div id="sections">
  <section id="top">
    <span class="text">I'm the most visible section!</span>
  </section>
  <section id="middle">
    <span class="text">I'm the most visible section!</span>
  </section>
  <section id="bottom">
    <span class="text">I'm the most visible section!</span>
  </section>
</div>
$(function () {
  var $sections = $('#sections').find('section');

  checkVisibility();

  $(window).on('scroll', function () {
      checkVisibility();
  });

  function checkVisibility() {
      $sections.removeClass('most-visible').mostVisible().addClass('most-visible');
  }
});

4. Decide whether to calculate visibility as a percentage of height.

mostVisible({
  percentage: false
})

5. Specify an offset to take into account when calculating visibility.

mostVisible({
  offset: 0
})

Changelog:

2019-11-16

  • v1.4.0: Remove unused arg

2019-01-18

  • v1.4.0: added offset option

This awesome jQuery plugin is developed by andyexeter. For more Advanced Usages, please check the demo page or visit the official website.