element.onclick = function() { alert(1); }
alert(element.onclick);
The above code will output function () { alert(1); }
Then I continue to execute the following code:
element.addEventListener('click', function() { alert(2); }, false);
alert(element.onclick);
The output is still function () { alert(1); }
In fact when clicking on the element now, the code addEventListener('click', function() { alert(2); }, false);
works, it means the new function alert(2)
has written into the onclick
property of this element. But why is the output still unchanged?
So, what I want to know is when executing addEventListener
, how the onclick
property changed?
Looking forward to your reply.
element.onclick = function() { alert(1); }
alert(element.onclick);
The above code will output function () { alert(1); }
Then I continue to execute the following code:
element.addEventListener('click', function() { alert(2); }, false);
alert(element.onclick);
The output is still function () { alert(1); }
In fact when clicking on the element now, the code addEventListener('click', function() { alert(2); }, false);
works, it means the new function alert(2)
has written into the onclick
property of this element. But why is the output still unchanged?
So, what I want to know is when executing addEventListener
, how the onclick
property changed?
Looking forward to your reply.
Share Improve this question edited Jan 16, 2022 at 9:58 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Mar 27, 2011 at 13:41 lichgolichgo 5332 gold badges6 silver badges16 bronze badges 3- I made a fiddle for this: jsfiddle/billymoon/9sNqq – Billy Moon Commented Mar 27, 2011 at 13:48
- Also - when both click handlers are added, they both run, not just the second, so adding event listener does not remove previous. It seems that element.onclick is only returning the first click event function. – Billy Moon Commented Mar 27, 2011 at 13:50
- That will help you: developer.mozilla/en/DOM/element.addEventListener#Notes – jasssonpet Commented Mar 27, 2011 at 13:53
2 Answers
Reset to default 7OnClick is a DOM Level 0 property. AddEventListener is part of the DOM Level 2 definition. Adding an event handler via the AddEventListener method does not change the OnClick property on the element, rather it adds the listener to a collection of event listeners on the element. You can find out more about DOM Level 2 events at http://www.w3/TR/DOM-Level-2-Events/events.html. There's also a nice article at http://en.wikipedia/wiki/DOM_events.
The "onfoo" attributes are independent of the event handler management system accessed via "addEventListener()". It's best to use one or the other, not both, and the right choice is the more flexible and unintrusive "addEventListener()" (where available).