just starting with JavaScript and trying to teach myself through simple exercises. I have made this very simple little program which works as expected:
<!DOCTYPE html>
<html>
<head>
<title>Exercise</title>
<script type="text/javascript">
function doSomething(){
alert("you clicked the text");
}
</script>
</head>
<body>
<p id="text" onclick="doSomething()"> This is some text </p>
</body>
</html>
When you click the text, the alert appears. Then I have modified it slightly to this:
<!DOCTYPE html>
<html>
<head>
<title>Exercise 2</title>
<script type="text/javascript">
var whenClicked = document.getElementById("text");
whenClicked.onclick = doSomething();
function doSomething(){
alert("you clicked the text");
}
</script>
</head>
<body>
<p id="text"> This is some text </p>
</body>
</html>
Expecting it to work exactly in the same way, but when I load the document on the web browser, the alert appears straight away, without me clicking on the text. Why is this happening? Thanks P.