onScroll

The onScroll function attaches a scroll event listener to elements matching the specified selector. When the scroll event is triggered and meets the required conditions, the provided callback function

onScroll() - Adds a scroll event listener to the HTML element.

  • Recives:

    1. The minimum scroll amount required to trigger the callback. Default is 0

    2. The function to execute when the scroll amount is greater than or equal to the specified amount.

    3. Any additional condition to check before executing the callback (optional)

  • Returns:

    • The HTML element to which the scroll event listener was added.

$('.myContainer').onScroll(threshold, callback);

Parameters

  1. threshold (number)

    • The minimum scroll distance required (in pixels) before the callback function is executed.

    • Type: number

  2. callback (function)

    • A function to be executed when the scroll event is triggered and the threshold is met.

    Callback Parameters

    1. s (boolean)

      • Represents the status of the scrolling action.

      • Value:

        • true: Scrolling meets the conditions.

        • false: Scrolling does not meet the conditions.

    2. n (number)

      • The total amount scrolled since the last scroll event in pixels.

    3. e (object)

      • The native scroll event object, providing details about the scrolling action.

$('.container').onScroll(40, function (s, n, e) {
    if (s) {
        console.log(`Scrolled ${n} pixels.`);
    } else {
        console.log('Scroll threshold not met.');
    }

    // Access the event object
    console.log('Scroll event:', e);
});

Additional condition

  1. additionalCondition (function or expression) (optional)

    • Any additional condition to check before executing the callback function.

    • If provided, this condition is evaluated alongside the threshold condition. The callback executes only if this condition evaluates to true.

$('.container').onScroll(40, function (s, n, e) {
    if (s) {
        console.log(`Scrolled ${n} pixels.`);
    } else {
        console.log('Scroll threshold not met.');
    }

    // Access the event object
    console.log('Scroll event:', e);
}, function () {
    // Additional condition: Only execute if the window width is greater than 768px
    return $(window).width() > 768;
});

More Use cases

$('.container').onScroll(40,(s)=>{
   s?$('#side_btn').hide():$('#side_btn').show();
});

Last updated