-1

displayDate() function is automatically invoked when page loads.But when i call displayDate function without using parenthesis then it works perfectly.

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<p>Click "Try it" to execute the displayDate() function.</p>

<button id="myBtn">Try it</button>

<p id="demo"></p>

<script>
document.getElementById("myBtn").onclick = displayDate();

function displayDate() {
    document.getElementById("demo").innerHTML = Date();
}
</script>

</body>
</html> 

This code sample is from w3schools

Skyyy
  • 1,539
  • 2
  • 23
  • 60

3 Answers3

1

@Juergen is correct above, but another easy way of handling this is to just declare the function directly:

document.getElementById("myBtn").onclick = function() {
    document.getElementById("demo").innerHTML = Date();
}

Obviously this assumes you aren't trying to reuse the function, but it is usually a little cleaner.

Brian
  • 1,513
  • 2
  • 14
  • 17
0

This statement calls the displayDate function and assigns the return value to the onclick attribute of "myBtn".

document.getElementById("myBtn").onclick = displayDate();

A better way to set the event handler would be:

document.getElementById("myBtn").addEventListener("click",displayDate);
user2182349
  • 9,569
  • 3
  • 29
  • 41
0

When you write a function with parentheses, it is invoked immediately. That is so in JavaScript and also in other languages.

When you install a an event-handler (and that is what you do), than you don't want to invoke the function, but tell which function to use, when the event happens. So you don't use the parentheses in this case, since you don't want to invoke the function right on, but tell what should be invoked later.

So, don't write the parentheses to install an event-handler.

Juergen
  • 12,378
  • 7
  • 39
  • 55