Detect Scroll Direction & Position In jQuery

File Size: 10.6 KB
Views Total: 1171
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Detect Scroll Direction & Position In jQuery

scrollDetection is a tiny jQuery plugin that detects scroll direction (up & down) and scroll position and adds CSS classes to specific indicator elements accordingly.

See also:

How to use it:

1. Insert the main script jquery.scroll-direction.js after loading jQuery library and we're ready to go. Note that jQuery is now OPTIONAL since v2.0.

<script src="/path/to/cdn/jquery.slim.min.js"></script>
<script src="/path/to/jquery.scroll-direction.js"></script>

2. Initialize the plugin to activate the scroll direction & position tracker.

// jQuery
$.scrollDirection.init({
  // options here
})

// Vanilla JS
window.scrollDirection.init({
  // options here
});

3. Determine whether to consider top and bottom offsets when tracking.

$.scrollDirection.init({
  
  // top offset in px
  topOffset: 0,
  
  // bottom offset in px
  bottomOffset: 0,
  
  // consider bottom as middle
  atBottomIsAtMiddle: true
  
})

4. Add custom CSS classes to the indicator element (default: body) while scrolling.

$.scrollDirection.init({
  
  indicator: true,
  indicatorElement: $("body"),
  scrollUpClass: "scroll-up",
  scrollDownClass: "scroll-down",
  scrollAtTopClass: "scroll-top",
  scrollAtMiddleClass: "scroll-middle",
  scrollAtBottomClass: "scroll-bottom",
  
})

5. Add custom CSS classes to an extra indicator element when scrolling past it.

$.scrollDirection.init({
  
  extraIndicators: {
    "element": $("#extra-element"), 
    "class": "custom-class",
  }

})

6. Available events that will be fired based on the current scroll direction & position.

$(window).on("scrollDirection", function () {
  // on load, resize, or scroll
});

$(window).on("scrollUp", function () {
  // on scroll up
});

$(window).on("scrollDown", function () {
  // on scroll down
});

$(window).on("scrollAtTop", function () {
  // when reaching the top
});

$(window).on("scrollAtMiddle", function () {
  // when reaching the middle zone
});

$(window).on("scrollAtBottom", function () {
  // when reaching the bottom
});

7. Available properties.

if($.scrollDirection.isScrollUp){
  // is scrolling up
}

if($.scrollDirection.isScrollDown){
  // is scrolling down
}

if($.scrollDirection.isScrollAtTop){
  // is reaching the top
}

if($.scrollDirection.isScrollAtMiddle){
  // is reaching the middle zone
}

if($.scrollDirection.isScrollAtBottom){
  // is reaching the bottom
}

Changelog:

v2.0.0 (2022-02-15)

  • Add jQuery-free ability.
  • Add minified version

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