Reputation: 10400
What is the difference between these two:
document.form1.colorButton.onclick = setBGColor;`
and
<input name="colorButton" type="button"
value="Change background color"
onclick="setBGColor();"/>`
When adding it to the attribute there are () but when using the DOM no (). Why is this?
Any referencea to official documentation would help.
Upvotes: 1
Views: 54
Reputation: 340055
In the .onclick
version, you are directly assigning a reference to a JS function reference to the .onclick
property. It would be an error to supply the parentheses because that would result in the function being called immediately and its result being assigned to the event handler.
In the "inline" DOM0 method, the resulting code is more like:
document.form1.colorButton.onclick = function onclick(event) {
setBGColor();
}
and in fact this is exactly what you'd see in a Chrome console if you used the inline method and then looked at the value of document.form1.colorButton.onclick
.
To explain further, the body of the onclick
attribute is wrapped up inside a new function and then the reference to that is assigned to the property. You must supply the parentheses otherwise the setBGColor()
function would not be invoked.
Upvotes: 2