Moving Ball Solution
Here’s the full source for the moving ball program we wrote last night:
[sourcecode language=”html”]
<html>
<header>
<script langauge="javascript">
function viewBall(){
document.images[‘ball1’].style.visibility = "visible";
}
function hideBall(){
document.images[‘ball1’].style.visibility = "hidden";
}
function goRight() {
document.images[‘ball1’].style.left =
parseInt(document.images[‘ball1’].style.left)+5 +"px";
}
function goLeft() {
document.images[‘ball1’].style.left =
(parseInt(document.images[‘ball1’].style.left)-5) +"px";
}
function computeWin(){
if(document.body.clientWidth) {
this.windWidth=document.body.clientWidth;
this.windHeight=document.body.clientHeight;
} else {
this.windWidth=window.innerWidth;
this.windHeight=document.innerHeight;
}
return this;
}
var timer;
function startTimer()
{
stopTimer();
timer=setInterval(‘animBall()’, 80);
}
function stopTimer()
{
if(timer != null){
clearInterval(timer);
}
}
function animBall() {
imgLeftInt = parseInt(document.images[‘ball1’].style.left);
imgWidth = parseInt(document.images[‘ball1’].width);
winWidth = parseInt(computeWin().windWidth);
if (imgLeftInt < (winWidth-imgWidth)){
goRight();
} else {
stopTimer();
}
}
</script>
</header>
<body>
<img src="ball.gif" id="ball1" style="position:absolute;top:
390px; left: 200px; visibility: hidden;"/>
<a href="#" onclick="viewBall()">Show Ball</a></p>
<a href="#" onclick="hideBall()">Hide Ball</a></p>
<a href="#" onclick="goRight()">Move It</a></p>
<a href="#" onclick="startTimer()">Start It</a></p>
<a href="#" onclick="stopTimer()">Stop It</a></p>
</body>
[/sourcecode]
Nick.