0

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.

Paul
  • 1,045
  • 4
  • 22
  • 46
  • 2
    (Once you fix that, your next problem is explained [here](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element)) – Quentin Sep 02 '16 at 10:18
  • #Skillz @Quentin :) – Liam Sep 02 '16 at 10:18
  • Great @Quentin for mentioning what'll be his immediate next question – Mr.7 Sep 02 '16 at 10:23

1 Answers1

0

there´s on little error in your code. you have to change:

whenClicked.onclick = doSomething();

to

whenClicked.onclick = doSomething;

this is happening because when the brackets are there the function get´s executed imidiatly