Hi all, I am new here and am just starting studying Javascript from the Headfirstlabs book. Please see my coding below as per the instructions on page 26, the only thing that happens is the onload alert [Hello, I am your pet rock] when the page loads, nothing else and no touchrock function or smiling face, I have the images where they should be and have attached them here. Can anyone tell me why it’s not working on my end please?
<html>
<head>
<title>irock -The virtual Pet Rock</title>
<script type="text/javascript">
function touchrock () {
var username = prompt ("What is your name?", "Enter your name here.");
if (username) {
alert ("It is good to meet you, " + username + ".");
document.getElementByID ("rockImg").src = "rock_happy.png";
}
}
</script>
</head>
<body onload="alert ('Hello, I am your pet rock.');">
<div style="margin-top: 100px; text-align: center;">
<img id="rockIMG" src="rock.png" alt="irock" />
</div>
</body>
</html>
Your touchrock function is not being triggered by anything at all (not onload of something, or on a mouse/keyboard action). That function must be triggered somehow, such as if you click on the rock.
Second, you really shouldn’t put event listeners (onload) inside a tag. If all your code has to be within the html page, then I would place a “script” tag just before the closing BODY tag, that would look something like this:
<script>
alert(‘Hello, I am your pet rock.’);
function touchrock() {
var username = prompt("What is your name?", "Enter your name here.");
if(username) {
alert ("It is good to meet you, " + username + ".");
document.getElementByID ("rockImg").src = "rock_happy.png";
Yes, it was my fault in copying over the code from the book, I made a few mistakes especially with case sensitive issues. I am truly very sorry guys, it works now but for future references I will search for the code from Headfirst as suggested then post that here, thanks!
The above 2 pieces of code, why are there two different codes to point to the images? Depending on the answer please explain if the top piece of code is the general code used that purpose?