shrewdbeans
shrewdbeans

Reputation: 12529

jQuery / JavaScript: Check if number is greater than another number by a minimum amount

I have a function that fires only if a user has scrolled left or right, by doing the following:

var currentScrollLeft = visibleArea.scrollLeft();

visibleArea.scroll(function () {
    var newScrollLeft = visibleArea.scrollLeft();

    if (newScrollLeft > currentScrollLeft) {
        // do something
    }
});

But this fires after even the slightest change in scrollLeft. Is there a way I can tell it to only fire if it's moved more than a certain amount, say 50?

Upvotes: 1

Views: 2421

Answers (1)

Mahn
Mahn

Reputation: 16585

if((Math.abs(newScrollLeft - currentScrollLeft)) > 50)

So your code above would become:

var currentScrollLeft = visibleArea.scrollLeft();

visibleArea.scroll(function () {
    var newScrollLeft = visibleArea.scrollLeft();

    if (Math.abs(newScrollLeft - currentScrollLeft) > 50) {
        // do something
    }

    currentScrollLeft = visibleArea.scrollLeft();
});

Upvotes: 3

Related Questions