Dora
Dora

Reputation: 6988

onclick function works but onsubmit doesn't

I am trying to make a submit button that when it is clicked then the image will move and another button that when it is clicked the image will reset.

Somehow if I do it with onclick function and the image will move and things are good, but if I use it with onsubmit function then it wouldn't work. Anyone can give me an idea why?

This is what I have for my script:

function catMoveRight()
{
    document.getElementById("cat").style.left=parseInt(document.getElementById("cat").style.left)+1+"px";
}

window.onload=function()
{
    catTimer = null;

    document.getElementById("start").onsubmit=function()
    {
        if(catTimer == null)
        {   
            catTimer = setInterval("catMoveRight()",1000);
        }

    }

}

This is my HTML body:

<img src="cat.jpg" id="cat" style=" position: absolute; left: 10px;"/><br/>
<form action=" " method="post" id="start">
    <input type="submit" value="Start" style="position: absolute; left: 10px; top: 220px;" />
</form>

Upvotes: 0

Views: 2498

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126082

Make sure to cancel the default action of the form submit. One way is to return false from the event handler:

document.getElementById("start").onsubmit = function()
{
    if(catTimer == null)
    {   
        catTimer = setInterval(catMoveRight, 1000);
    }
    return false;
};

Also there's no need to pass a string to setInterval. Don't use eval where it's not necessary.

Example: http://jsfiddle.net/QD3ev/1/

Upvotes: 4

Related Questions