When the onclick
event handler for one element is set directly to the built-in function click
of another element the event silently fails to trigger, even though it work when using a user-defined intermediary function.
Similarly, when the onclick
event handler is set directly to the built-in function alert
it results in a TypeError: Illegal invocation
even though it works when using a user-defined intermediary function.
Strangely, when the onclick
event handler is set directly to console.log
it works as expected, despite this also being a built-in function.
What's going on with click
and alert
that makes direct assignment behave unexpectedly? Why does the addition of an anonymous function that simply forwards the call make any difference?
const div1 = document.getElementById("1");
const div2 = document.getElementById("2");
const div3 = document.getElementById("3");
const div4 = document.getElementById("4");
const div5 = document.getElementById("5");
const div6 = document.getElementById("6");
const indicator = document.getElementById("indicator");
indicator.onclick = function() {
if (indicator.style.background == "blue") {
indicator.style.background = "green";
} else {
indicator.style.background = "blue";
}
};
div1.onclick = function(event) {
indicator.click(event);
};
div2.onclick = indicator.click;
div3.onclick = function(event) {
alert(event);
};
div4.onclick = alert;
div5.onclick = function(event) {
console.log(event);
};
div6.onclick = console.log;
#indicator {
height: 100px;
width: 100px;
}
div {
cursor: pointer;
text-decoration: underline;
}
<div id="1">Set indicator color via function (works)</div>
<div id="2">Set indicator color directly (silently fails)</div>
<div id="3">Trigger alert via function (works)</div>
<div id="4">Trigger alert directly (fails with error)</div>
<div id="5">Trigger console log via function (works)</div>
<div id="6">Trigger console log directly (works)</div>
<div id="indicator"></div>