pth
pth

Reputation: 69

Prevent another mousescroll when page already is

I'm using this script for a onepage website:

$(document).ready(function () {
    var divs = $('.mydiv');
    var dir = 'up'; // wheel scroll direction
    var div = 0; // current div
    $(document.body).on('DOMMouseScroll mousewheel', function (e) {
        if (e.originalEvent.detail > 0 || e.originalEvent.wheelDelta < 0) {
            dir = 'down';
        } else {
            dir = 'up';
        }
        // find currently visible div :
        div = -1;
        divs.each(function(i){
            if (div<0 && ($(this).offset().top >= $(window).scrollTop())) {
                div = i;
            }
        });
        if (dir == 'up' && div > 0) {
            div--;
        }
        if (dir == 'down' && div < divs.length) {
            div++;
        }
        //console.log(div, dir, divs.length);
        $('html,body').stop().animate({
            scrollTop: divs.eq(div).offset().top
        }, 200);
        return false;
    });
    $(window).resize(function () {
        $('html,body').scrollTop(divs.eq(div).offset().top);
    });
});

But I can't figure out how to prevent another scroll until the one that is already scrolling is finished, and then make a lillte delay before next scroll is possible.

If you try to make a lot of scroll movement in fiddle it just scrolls with out stopping for each mydiv.

jsFiddle

Can somebody help me out?

Upvotes: 0

Views: 103

Answers (2)

insertusernamehere
insertusernamehere

Reputation: 23580

Here's a possible solution:

I added a variable to determine whether your script is running:

var running = false;

Toggle this variable with a timeout at the beginning of your function:

$(document.body).on('DOMMouseScroll mousewheel', function (e) {
    if (running) {
        return false;
    }

    running = true;
    setTimeout(function() {
        running = false;
    }, 1000);

    […]

Demo

Try before buy

Upvotes: 2

Joel Peltonen
Joel Peltonen

Reputation: 13412

Add a "scrolling" boolean flag and check if it's set. To get a delay, reset the flag after some time.

See http://jsfiddle.net/JqU2T/34/

Code example:

var scrolling = false;

$(document.body).on('DOMMouseScroll mousewheel', function (e) {
    if(scrolling) return false;
    scrolling = true;

    // your codes here...

    setTimeout(function() {
        scrolling = false;
    }, 5000); // delay of 5000ms

    return false;
});

Upvotes: 1

Related Questions