Trigger Custom Functions on Element Visibility with onScreen.js

File Size: 5.35 KB
Views Total: 48
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Trigger Custom Functions on Element Visibility with onScreen.js

onScreen is a lightweight jQuery plugin that allows you to trigger custom functions, like CSS3 animations or other interactions, when an element fully or partially enters the viewport.

Example: You have a set of images that you want to animate as they come into view. Instead of manually calculating scroll positions, attach onScreen to each image. The plugin will trigger your animation function only when the image is sufficiently visible.

onScreen vs. Intersection Observer API

The native Intersection Observer API is powerful, but might be overkill for simpler tasks. It requires more setup code. onScreen provides a jQuery-style syntax, so it can be easier to integrate if you’re already working within a jQuery environment.

Unlike the Intersection Observer API, onScreen includes built-in scroll debouncing and viewport percentage calculations. It offers granular control through configuration options like percentOfElementOnScreen and percentOfScreenFilled. 

How it works:

This plugin works by monitoring the viewport and comparing the position of an element relative to the visible screen area. It uses the getOverlapPercent function to calculate the percentage of overlap between the element and the viewport. When the visibility criteria are met (based on options like percentOfElementOnScreen), it triggers the callback function.

How to use it:

1. Include both jQuery library and the onScreen plugin's script on the webpage.

<script src="/path/to/cdn/jquery.min.js"></script>
<script src="/path/to/jquery.onScreen.js"></script>

2. Initialize the plugin on the element you want to track. Define a callback function that will run when the element enters the viewport.

<div id="target">
  Element
</div>
let callback = function() {
  // do something here
}
$("#target").onScreen(callback);

3. Customize onScreen's behavior with these options:

$("#target").onScreen(callback,{

  // Delay before checking for on-screen elements after page load (in milliseconds).
  delayStart: 500,

  // Percentage of the element that must be visible to trigger the callback.
  percentOfElementOnScreen: 95,

  // Percentage of the screen that must be covered by the element.
  percentOfScreenFilled: 100,

  // Delay after a scroll event before checking element visibility (in milliseconds).
  stopScrollDelay: 10,

  // If true, the callback runs only once. If false, it runs every time the element meets the visibility criteria.
  runOnce: true,
  
});

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