onScroll

The onScroll function makes it easy to track how far a user has scrolled on a webpage. It lets you specify a scroll threshold, a callback function to run when the threshold is reached, and even an optional condition to check before the callback runs.


How It Works

  • Scroll Threshold: Decide how many pixels a user must scroll before your callback is triggered.

  • Callback: A function that will run when the scroll conditions are met.

  • Condition: Optionally add a custom condition for more control.


Syntax

onScroll(threshold, callback, condition);

Parameters

  1. threshold (number):

    • The number of pixels a user needs to scroll before the callback runs.

    • Default is 0 (callback triggers immediately on any scroll).

  2. callback (function):

    • A function to execute on each scroll event. It receives the following:

      • status (boolean): Whether the conditions are met (true or false).

      • scrolled (number): How many pixels the user has scrolled.

      • event (object): The native scroll event object.

  3. condition (boolean or function) - (optional):

    • An extra condition that must be true for the callback to run.

    • Default is null (ignored if not provided).


Examples

1. Run a function when scrolled 100 pixels

onScroll(100, function (status, scrolled, e) {
  if (status) {
    console.log(`Scrolled ${scrolled} pixels!`);
  }
});

2. Add an extra condition

onScroll(200, function (status, scrolled, e) {
  if (status) {
    console.log(`Scrolled ${scrolled} pixels and condition met!`);
  }
}, window.innerWidth > 768);

More use cases

show and hide nav bar when user scroll pass 400px

onScroll(400,function (s,n,e) {
    s?$('#navbar').hide():$('#nabar').show();
});

Last updated