I am trying to count to 0 from any given number on mouseup
to animate the src
attribute of an img
tag.
var count = 0,
direction = 1,
image = document.getElementById('myImage'),
mousedownID = -1;
function mousedown(event) {
if(mousedownID==-1)
mousedownID = setInterval(whilemousedown, 150);
}
function mouseup(event) {
if(mousedownID!=-1) {
mousedownID = setInterval(after, 150);
clearInterval(mousedownID);
mousedownID=-1;
}
}
function whilemousedown() {
image.src = "block-" + count + ".png";
count += direction;
direction *= (((count % 11) == 0) ? -1 : 1);
}
function after() {
image.src = "block-" + count + ".png";
count = count - 1;
if(count = 0){
clearInterval(mousedownID);
}
}
document.addEventListener("mousedown", mousedown);
document.addEventListener("mouseup", mouseup);
document.addEventListener("mouseout", mouseup);
While the mouse is clicked, 12 images being animated, 1 … 12 … 1 … 12 … and so on, now i'd like to animate it back to the first image, once i released the mousebutton.
You can use two setInterval, one just to increase/decrease, and another just to decrease:
var limit = 11,
count = 0,
direction = -1,
image = document.getElementById('myImage'),
mousedownID = -1,
mouseupID = -1;
function mousedown(event) {
if(mousedownID == -1) {
if (mouseupID != -1) {
clearInterval(mouseupID);
mouseupID = -1;
}
mousedownID = setInterval(whilemousedown, 150);
}
}
function mouseup(event) {
if(mousedownID != -1) {
clearInterval(mousedownID);
mousedownID = -1;
if (mouseupID == -1) {
direction = -1; // delete this if you prefer
mouseupID = setInterval(after, 150);
}
}
}
function whilemousedown() {
image.src = "block-" + count + ".png";
if (count == 0) {
direction = +1;
} else if (count == limit) {
direction = -1;
}
count += direction;
}
function after() {
if (count == 0) {
clearInterval(mouseupID);
mouseupID = -1;
return;
}
count = count - 1;
image.src = "block-" + count + ".png";
}
document.addEventListener("mousedown", mousedown);
document.addEventListener("mouseup", mouseup);
document.addEventListener("mouseout", mouseup);