DOM - element.onclick


#1

When I called the function using element.onclick = turnButtonRed(); it was denied, however calling it as element.onclick = turnButtonRed; worked. I was wondering why the parenthesis were deemed unecessary when calling the function.

Here is the code that was accepted:

let element = document.querySelector(“button”);

function turnButtonRed () {
element.style.backgroundColor = ‘red’;
element.style.color = ‘white’;
element.innerHTML = ‘Red Button’
}

element.onclick = turnButtonRed;

Here is the link to the exercise: https://www.codecademy.com/paths/web-development/tracks/building-interactive-javascript-websites/modules/web-dev-interactive-websites/lessons/javascript-dom/exercises/onclick-element


#2

Because we do not invoke it on the listener. The listener invokes it when triggered by a click event.

element.onclick = turnButtonRed;

turnButtonRed is known as callback. Only a reference to the function is assigned to the listener, not the return value.