-2

In the following code, once I run it, it waits for click event to fire an alert. However if I change the following javascript code

from

clickMeButton.onclick=runTheExample;

to

clickMeButton.onclick=runTheExample();

it always fires up an alert when page downloaded without any click event. I would like to know what is the difference. I am using Chrome. Snipped code is as follows:

<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
    <script type="text/javascript" src="script13.js">   </script>
</head>

<body>
    <h1 id="title">DOM Example </h1>
    <p id="first">This is the first paragraph</p>
    <p id="second"><strong>This is the second paragraph</strong></p>
    <p id="third">This is the third paragraph</p>
    <input type ="text" id="myTextBox" />
    <input type ="submit" id="clickMe" value="Click Me!"/>
    <a href="http://www.google.com" id="MyGoogle"> Google! </a>
</body>
</html>

//script13.js
window.onload= function(){
var clickMeButton=document.getElementById('clickMe');
clickMeButton.onclick=runTheExample;
}

function runTheExample(){
alert('running the example');
}
jub0bs
  • 60,866
  • 25
  • 183
  • 186
casillas
  • 16,351
  • 19
  • 115
  • 215
  • 1
    I think when you call var x = func() you are executing the function and making the var x = return of function execution. And when you call var = func you are only saying that the var x is now your function. – Diogo Silva Oct 24 '14 at 15:14
  • In the 2nd notation `clickMeButton.onclick` is assigned to **returning value** of `runTheExample()`, whereas it expects **reference** to a function (`runTheExample`) – hindmost Oct 24 '14 at 15:18

1 Answers1

3
var x = func(); //Means you execute the function and output its return value to x;

var x = func; //Means you attribute the function to the variable, so you can call it, using x.

Example

function f(){
 return 4;
}

var x = f(); // x = 4
var x = f; // x = f()
Diogo Silva
  • 301
  • 3
  • 8