How to Make a "Ball" move When a Button is Clicked.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mkay1
    New Member
    • Jan 2012
    • 1

    How to Make a "Ball" move When a Button is Clicked.

    When the up or down button is clicked I want the "ball" to move up or down. What I have sort of works. When I click up it will move up only ONCE and down only ONCE I want to be able to keep clicking up or down (or left or right) and have it keep moving by 5 pixels. Here's my js code. I have it positioned absolutely in my htm file.

    Code:
    window.onload = initAll; 
    
    function initAll() 
    {
    	myBallObj=document.getElementById("ball"); 
    	myBallObj.style.top = "300px";
    	myBallObj.style.left = "300px";
    	
    	document.getElementById("btnUp").onclick = moveBall;
    	document.getElementById("btnDown").onclick = moveBall;
    	functions	
    }
    
    function moveBall()
    {
    	var y = parseInt(myBallObj.style.left); 
    	switch(this.id)
    	{
    		case "btnUp": y -= 5; break;
    		case "btnDown": y += 5; break; 
    	}
    	
    	myBallObj.style.top = y += "px"; 
    	
    }
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    You'll want to use the setInterval() function to call your animation function every so often.

    Comment

    Working...