Hello,
I’m doing my homework now and onclick event drives me crazy.
My intention is when a user clicks an answer(red, green or blue icon), onclick event is triggered and an alert message shows up saying it’s right or not.
However when the window loads, the onclick event is triggered automatically even though it’s not clicked. I don’t know what’s wrong.
My html code is…
<div id=”questions”>
<h2> What do you think my favorite color is?</h2>
<br />
<span id=”red”><img src=”../images/red.png” /> </span>
<span id=”green”><img src=”../images/green.png” /></span>
<span id=”blue”><img src=”../images/blue.png” /></span>
</div>
My javascript code is…
// JavaScript Document
window.onload = load;
var username;
function load() {
username = prompt(“Please enter your name : “, “”);
if (username == “”) {
username = “Guest”;
}
writeUsername();
firstQuestion();
}
// if a user enters name, it shows on the page.
function writeUsername() {
document.getElementById(“username”).innerHTML = “Hello, ” + username + “! Welcome to my site!!!”;
}
function firstQuestion() {
document.getElementById(“red”).onclick = incorrect();
document.getElementById(“green”).onclick = incorrect();
document.getElementById(“blue”).onclick = correct();
}
function secondQuestion() {
}
function correct() {
alert(“answer is right”);
}
function incorrect() {
alert(“answer is wrong”);
}