0

After two days of effort and research, I can't seem to figure out how to get onClick to work with an image.

Here's my html:

<!DOCTYPE html>
<html>
    <title>Stupid F'ing Rock!</title>
 <head>   
    <link type="text/css" rel="stylesheet" href="stylesheet.css"/>
    <script src="script.js"></script> 
</head>

    <body>
        <img id="touchRock" src="images/rock_unhappy_original.png">
    <body/>
</html>

And here's the code in my js file:

/*global alert */


window.onload = function () {
    alert("Hello, I am your pet rock!");
};
document.getElementById("touchRock").onclick = function () {
    prompt("What is your name?");
};

The only thing that works in the JS file is the alert function. I also have the following errors:

5       Missing 'use strict' statement.  alert("Hello, I am your pet rock!");
8   Missing 'use strict' statement.  prompt("What is your name?");
8   'prompt' was used before it was defined.     prompt("What is your name?"); 

Anyone know what I'm doing wrong?

1 Answers1

1

You need to assign the onclick function inside the onload function, because you're loading the JS file before the body has been loaded and the ID doesn't exist yet.

window.onload = function() {
    alert("Hello, I am your pet rock!");
    document.getElementById("touchRock").onclick = function() {
        prompt("What is your name?");
    };
};
Barmar
  • 741,623
  • 53
  • 500
  • 612