Function help! Spinning image on click event not working (Solved)

Function help! Spinning image on click event not working (Solved)
0

#1

Hi there, I am currently creating a website for a guy. He wants a feature which I am trying to implement and failing. I basically want to spin an image on a click event. For some reason, every time the page loads, the code in my js file runs before the object is clicked! I am completely puzzled and maybe one of you could help me out with where I am going wrong. Thanks in advanced!

var looper;
var degrees = 0;
function rotateAnimation(el,speed){

    var elem = document.getElementById(el);
    
    elem.style.transform = "rotate("+degrees+"deg)";

    if(degrees < 90){
        looper = setTimeout('rotateAnimation(\''+el+'\','+speed+')',speed);
        degrees++;
    }
    document.getElementById("status").innerHTML = "rotate("+degrees+"deg)";
}

document.getElementById("img1").addEventListener("click", rotateAnimation("img1", 100));

#2

The function’s executed instantly because of the brackets. If you would remove them it would stop doing that however you need them since you have some parameters in there so you will have to put the function inside a “closure” instead.

Solution

document.getElementById(“img1”).addEventListener(“click”, function() { rotateAnimation(“img1”, 100) });

Source:
http://stackoverflow.com/questions/1300242/passing-a-function-with-parameters-as-a-parameter


#3

Thanks heaps Quickz! That was my problem, not being able to figure out how to pass my parameters. Thanks a bunch :smiley: