jQuery Plugin To Add CSS Classes To Elements When Scrolling - scrollClass

File Size: 5.26 KB
Views Total: 3097
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
jQuery Plugin To Add CSS Classes To Elements When Scrolling - scrollClass

scrollClass is a jQuery plugin that adds user specified CSS class(es) to html elements and executes a callback when they're scrolled into view, with configurable delay, threshold and top offset options. Great for scroll-triggered element animations or image lazy load.

How to use it:

1. Load the latest jQuery library and jQuery scrollClass plugin at the end of the html document.

<script src="//code.jquery.com/jquery.min.js"></script>
<script src="scrollClass.js"></script>

2. Use data-scroll-class to specify the CSS class applied to the element when it is scrolled into view. In this case, we're going to use Animate.css to create a 'swing' animation effect when scrolling down.

<div class="animated" data-scroll-class="swing">
  ...
</div>

3. Call the function and done.

$('.animated').scrollClass();

4. Delay the loading of images using the jQuery scrollClass plugin's custom callback function.

$('.image').scrollClass({
  callback: function () { //lazy load images
    var selector = $(this);
      var img = $("<img />").attr('src', $(this).data("img")).one('load', function() {
      selector.append(img);
    });
  }
});

5. Default plugin options.

$('.el').scrollClass({

  // set CSS class after 10 milliseconds delay
  delay: 20,

  // set CSS class when 50% of element enters the viewport
  threshold: 50,

  // number of pixels to offset elements from the top of the window
  offsetTop: 0,

  // reset the element after it leaves the viewport
  reset: false,

  // the frequency at which the script runs while scrolling the page
  throttle: 50,
  
});

Changelog:

2022-02-04

  • Added data-scroll attributes, added throttle, added reset

2018-05-21

  • Refactored delay option, added listener for load, updated version

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