Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 784
lichgo Avatar asked Mar 27 '11 13:03

lichgo


People also ask

What is the benefit of the addEventListener () method?

The addEventListener() method makes it easier to control how the event reacts to bubbling. When using the addEventListener() method, the JavaScript is separated from the HTML markup, for better readability and allows you to add event listeners even when you do not control the HTML markup.

How does Onclick work in JavaScript?

The onclick event executes a certain functionality when a button is clicked. This could be when a user submits a form, when you change certain content on the web page, and other things like that. You place the JavaScript function you want to execute inside the opening tag of the button.

Is addEventListener the same as on ()?

addEventListener() is a method of a normal DOM element and . on() is a jQuery object method. As you probably know, a jQuery object can represent more than one element and when you use the . on() method you are attaching and event handler to every element in the collection.


2 Answers

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.

like image 103
tvanfosson Avatar answered Oct 31 '22 14:10

tvanfosson


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

like image 22
Pointy Avatar answered Oct 31 '22 15:10

Pointy