When you add an event handler to an element the function to be called runs with that element as context. This means that the this
within this function is the element to which you added the event handset.
This function automatically receives an argument, the event that occurred that caused the function to be invoked. This event is an object with multiple properties, one of which .target
is the element where the event started.
Let's look at this HTML example:
section
div
span
where span is inside div which in turn is within section.
When you do:
section.addEventListener('click', function(e){
This function will be run whenever there is a click on the section but also on one of its descendants. In fact all parent elements whose offspring have a triggered event see their addEventListeners
to be called as well. You can avoid this by invoking e.preventPropagation();
within the function. If this aside, and returning to the example above, this function will have as this
always the section and as e.target
always the element that receives click
.
Take a look at this example ( link ), where I create a way to verify this:
var section = document.querySelector('section');
section.addEventListener('click', handler(section));
function handler(elComAuscultador) {
return function(e) {
var target = e.target.tagName.toLowerCase();
var self = this.tagName.toLowerCase();
var log = [
'Clicaste no elemento ' + target,
'O this é o elemento ' + self,
'this == elComAuscultador é verdadeiro? ' + (this == elComAuscultador ? 'sim' : 'não')
];
alert(log.join('\n'));
}
}
body > * {
padding: 50px;
}
section {
background-color: blue;
}
div {
background-color: yellow;
}
p {
background-color: red;
width: 100px;
height: 100px;
}
<section>section
<div>div<p>span</p></div>
</section>
Applies the same logic using section.onclick = function(e){
( example ) but with a fatal difference > is that this elemento.onclick = function(){
method only allows one per element and overrides all others ( example ), while elemento.addEventListener
allows as many headphones as you want, and calls everyone when the event happens.