Infra Stank
Infra Stank

Reputation: 816

Mousedown scroll function not working

I've got a button that is intended to scroll down a div when the mouse button is clicked and held on it . I thought this should work but it only scrolls one px per click as oppose to scrolling until the mouse up event .

code:

 var howfar = 0;
    $('#scrolldown').mousedown(function() {

        howfar ++;
        $('#scrollbox').scrollTop(howfar);

    });

Upvotes: 1

Views: 2628

Answers (3)

ShankarSangoli
ShankarSangoli

Reputation: 69915

Keeping mousedown continously doesn't mean it will fire that event continously, it will only fire once. What you can do it start increasing the scrollTop once mousedown event triggers using setInterval and then clear the interval on mouseup event.

Try something like this.

var howfar = 0;
var timer;
$('#scrolldown').mousedown(function() {
    var innerHeight = $('#scrollbox').css('height', 'auto').height();
    $('#scrollbox').css('height', '100px');
    timer = setInterval(function(){
        if(howfar < innerHeight){
            $('#scrollbox').scrollTop(howfar++);
        }
        else{//Clear the interval
            clearInterval(timer);
        }
    }, 10);
});
$('#scrolldown').mouseup(function() {
     clearInterval(timer);
});

Demo

Upvotes: 1

DarkAjax
DarkAjax

Reputation: 16223

You could try something like this

Upvotes: 0

Paul
Paul

Reputation: 12440

I think this is what you are looking for:

var shouldScrool = false
    takeAction,
    count = 0;

takeAction = function() {
   count = 0;
   while(takeAction) {
        count++;
        $('#scrollbox').scrollTop(count);
   }
};
$('#scrolldown').mousedown(function() {
    takeAction = true;
    takeAction();
});

$('#scrolldown').mouseup(function() {
    takeAction = false;
});

Upvotes: 3

Related Questions