lichgo
lichgo

Reputation: 533

How addEventListener influences the onclick property of DOM element?

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.

Upvotes: 5

Views: 3121

Answers (2)

tvanfosson
tvanfosson

Reputation: 532515

OnClick 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.org/TR/DOM-Level-2-Events/events.html. There's also a nice article at http://en.wikipedia.org/wiki/DOM_events.

Upvotes: 7

Pointy
Pointy

Reputation: 413757

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).

Upvotes: 2

Related Questions