When to use this and when to use event.target

2

Today a question came up, although with the tests I did I managed to solve several of them.

But so, when should I use e.target and when should I use This . Because yesterday when I discovered e.target, I started to use it. But the downside, is that this one I need to check where I am clicking to do the given event. But I noticed that it is very useful when I use the event in $(document) .

Another disadvantage of this is that I should point to the element (say I have divs with the same classes as child), I have to determine if it's the first, second etc, I at least could not get a child from THIS that was clicado , or a PAI element, without pointing out what it was. I had to give find to specify which one I wanted.

These are my perseptions. I would like to hear from you, when should I use each one.

link

    
asked by anonymous 12.05.2015 / 00:14

1 answer

3

When you use one or the other depends on what you want.

If you use for example:

<div>
    <button onclick="clicaMe(event);">Clica-me!</button>
</div>

and in JavaScript

var el = document.querySelector('div');

function clicaMe(e) {
    console.log('inline this', this); // vai dar window
    console.log('inline e.target', e.target); // vai dar button
}
el.onclick = function (e) {
    console.log('onclick this', this); // vai dar el, ou seja "div"
    console.log('onclick e.target', e.target); // vai dar button
}
el.addEventListener('click', function (e) {
    console.log('event handler this', this); // vai dar el, ou seja "div"
    console.log('event handler e.target', e.target); // vai dar button
});

jsFiddle: link

Note that when you run a function via onclick inline in HTML the scope of this will be window . In other cases the this is the very element that received the eventhandler or onclick. The e.target is always the concrete element that received the click, descending from the element to which the event handler was tied if the click was triggered on it.

There is another parameter to take into account: bubbling (or event propagation).

Notice this example:

var el = document.querySelector('div');
var btn = document.querySelector('button');

el.addEventListener('click', function (e) {
    console.log('div this', this); // vai dar el, ou seja "div"
    console.log('div e.target', e.target); // vai dar button
});
btn.addEventListener('click', function (e) {
    console.log('button this', this); // vai dar button
    console.log('button e.target', e.target); // vai dar button
});

jsFiddle: link

In this case both event handlers are triggered because once the button receives the click it propagates the event to the parent elements, and firing their eventhandlers along that path. Also notice that the eventhandler of btn fires first!.

This can be useful for distinguishing between this and e.target when you want to know in detail which element is clicked.

    
12.05.2015 / 00:25