Advanced Element Visibility Detector In jQuery - observe.js

File Size: 3.7 KB
Views Total: 643
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Advanced Element Visibility Detector In jQuery - observe.js

observe.js is an advanced element visibility detector that provides a simple way to execute certain callback functions when an element is visible/invisible, or has ever been in the viewport.

Similar to the Intersection Observer API but with better flexibility and browser compatibility.

Ideal for lazy loading images when they become visible, loading more content as a trigger element has scrolled into view, animating elements once they enter the viewport, and much more.

How to use it:

1. Put the main JavaScript library after loading jQuery library and we're ready to go.

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

2. Execute a callback function whenever a selected element enters the viewport.

<div class="box"></div>
$('.box').observe(function(){ 
  alert("I'm visible!"); 
});

3. In addition, the plugin automatically add corresponding CSS classes to the document based on the observer.

<html class="has-observers scrolled-past-top scrolled-to-bottom">

4. Execute a callback function whenever the element leaves the viewport.

$('.box').observe({
  'leave-viewport': function(){
    alert('leave-viewport')
  }
})

5. Execute a callback function when half of the element enters the viewport.

$('.box').observe({
  'enter-half-viewport': function(){
    alert('enter-half-viewport')
  }
})

6. Execute a callback function when half of the element leaves the viewport.

$('.box').observe({
  'leave-half-viewport': function(){
    alert('leave-half-viewport')
  }
})

7. Execute a callback function when the element has ever been in the viewport.

$('.box').observe({
  'observed': function(){
    alert('observed')
  }
})

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