Detect Most Visible Elements With jQuery - most-visible

Detect Most Visible Elements With jQuery - most-visible
File Size: 71 KB
Views Total: 1121
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="/path/to/cdn/jquery.slim.min.js"></script>
<script src="/path/to/dist/most-visible.min.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:

v2.0.0 (2021-12-23)

  • Restructured the plugin away from UMD into two separate files; for the browser (dist/most-visible) and a module for bundlers (js/most-visible).
  • Removed the ability to create an instance of the function with new mostVisible()
  • Renamed the makeJQueryPlugin function to makejQueryPlugin

2021-07-15

  • v1.5.0: Updated dependencies

2019-12-22

  • v1.5.0: Store constant value for viewportHeight before comparison

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.