2 March 2012: Move that Ball!
Well done to everyone who got this exercise working! For those who didn’t try copying the code below into NotePad++ and see how you get on.
We started by trying to hide and show this ball:
Remember, this is an “Animated GIF”, and that’s why it’s animated! It works like a cartoon – it has lots of image that are shown one after another and this is done automatically by the browser. To make a copy on your computer, right-click the image above and save to your desktop.
Here’s the code we started out with:
[sourcecode language=”HTML”]
<html>
<header>
<script language="javascript">
function viewBall(){
document.images[‘ball1’].style.visibility = "visible";
}
function hideBall(){
document.images[‘ball1’].style.visibility = "hidden";
}
</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>
</body>
[/sourcecode]
I’ve changed the way the anchor works from the code we used in the session. This should work on all browsers.
Remember that the ball will be hidden when the page is first loaded.
We then added some code that moves the ball a little to the right when you click the hyperlink:
[sourcecode language=”HTML”]
<html>
<header>
<script language="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";
}
</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>
</body>
[/sourcecode]
Let us know how you get on!
Nick Grattan.