Reputation: 3222
I am trying to trigger animations on "mousedown" and immediately stop it once the mouse is released.
On "mousedown" I set a flag to true which sets the condition for the animation of the corresponding button clicked. The problem is on "mouseup" I set the flag to false but the animation doesnt stop. I dont get any errors in my console so it seems to be a logical based mistake.
What is my mistake here and how can I fix this?
https://jsfiddle.net/b4kn4w3g/2/
The essential code:
function eventBundle(e) {
if (e.target !== e.currentTarget) {
if (e.target == parent.children[0]) {
isDown = true;
amount = "reduce";
} else if (e.target == parent.children[1]) {
isDown = true;
amount = "increase";
}
}
e.stopPropagation();
}
window.addEventListener("mouseup", function(){
isDown = false;
amount = "neutral";
});
function holdStuff() {
if (isDown == true && amount == "increase") {
maxValue += 100;
} else if (isDown == true && amount == "reduce") {
maxValue -= 100;
}
requestAnimationFrame(holdStuff)
}
Upvotes: 0
Views: 85
Reputation: 31
The animation doesn't stop on mouseup
because the update
function is still running periodically. You could do what Joseph said, or maybe cancel the updating when you don't need it. The requestAnimationFrame
returns an ID which you can save, like this:
requestID = window.requestAnimationFrame(callback);
and then you can cancel it like this:
cancelAnimationFrame(requestID);
Upvotes: 1
Reputation: 78590
add maxValue = minValue
to your mouseup
event listener. The issue is that your update function incrementally (by a value of 5) increases or decreases with minValue += 5;
and minValue -= 5;
. When you increase or decrease the max by 100, it has to eventually get there by increments of 5. Setting the maxValue to the current minValue stops the change at the current state.
window.addEventListener("mouseup", function(){
maxValue = minValue;
isDown = false;
amount = "neutral";
});
https://jsfiddle.net/nexrytes/
Upvotes: 3