Question

I wrote a code that shifts a slidebar and I want to improve it so while the user holds click down it keeps shifting. I wrote this code using help of different questions in this website. My problem is it falls to endless loop.

// The right button in the slidebar moves it to the right
var mouseStillDown = false;

function shiftToRight() {
    if (!mouseStillDown) { return; } 
    var cur = ($('#slideBar').position().left - $('#leftButton').outerWidth()) - $('.ingredient').outerWidth();
    // Checks if movement will cause the slidebar out of right edge
    if ($('#fixedPart').outerWidth() - cur > $('#slideBar').outerWidth()) {
        cur = $('#fixedPart').outerWidth() - $('#slideBar').outerWidth();
    }
    $('#slideBar').animate({ left: cur}, { duration: 500 , easing: "swing" } );
    if (mouseStillDown) { setTimeout(shiftToRight(), 500); }
};

$('#rightButton').mousedown(function() {
    mouseStillDown = true;
    shiftToRight();
}).mouseup(function() {
    clearInterval(mouseStillDown);
    mouseStillDown = false;
});

I also tried setInterval(shiftToRight(), 500) but the result was the same. it seems changing the flag in mouseup() is not read by the function.

Was it helpful?

Solution

Try the following

// The right button in the slidebar moves it to the right
function shiftToRight() {
    var cur = ($('#slideBar').position().left - $('#leftButton').outerWidth()) - $('.ingredient').outerWidth();
    // Checks if movement will cause the slidebar out of right edge
    if ($('#fixedPart').outerWidth() - cur > $('#slideBar').outerWidth()) {
        cur = $('#fixedPart').outerWidth() - $('#slideBar').outerWidth();
    }
    $('#slideBar').animate({ left: cur}, { duration: 500 , easing: "swing" } );
};

var rightIntervalId;
$('#rightButton').mousedown(function() {
    event.preventDefault();
    rightIntervalId = setInterval(shiftToRight, 500);
}).mouseup(function() {
    clearInterval(rightIntervalId);
}).click(function() {
    shiftToRight();
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top