Mr.Master Mr.Master - 2 months ago 11
HTML Question

Assign Events Using the HTML DOM JS

I am learning JS,and I have an example which I don't understand.
When we call functions like this it works:

<button onclick="displayDate()">Try it</button>


This also works:

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

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


But when I change this
displayDate
to
displayDate()
it shows me the date when page is loaded,so onclick doesn't work. My question is: why does JS DOM work like this? What is really happening? Do we not call a function like this:
function();
?

Answer

When you write:

something = functionName();

it means to call the function immediately, and then put the value that it returns into something.

When you write:

something = functioName;

it means to put a reference to the function into something, but not call it. This allows the function to be called later, using that reference. When something is someElement.onclick, this happens when the user clicks on the element.