What is the difference of $ (this) and $ (event.target)?

25

Well, a question arose while I was tinkering with jQuery and the code worked perfectly in Chrome using the $(event.target) event, already in Firefox it only worked with $(this) , so that doubt arose. What is the main difference between them?

$(document).on('click', '.bermuda', function(e){
    $(e.target).fadeOut(300);
});

$(document).on('click', '.bermuda', function(){
    $(this).fadeOut(300);    
});
    
asked by anonymous 19.02.2015 / 12:29

2 answers

15

The $(this) is exactly the current element, where the event was defined.

While $(event.target) can be both the element where the event is assigned and the child of this current element, where the event was defined.

JQuery example:

$(document).click(function(e){
    console.log(e.target); // #teste
    console.log(this); // #document
});

HTML example:

<body>
   <div id="teste">aqui será clicado</div>
</body>

In your case, if .bermuda has any child elements, such as <p> or <img/> , clicking on them will cause the .bermuda event to be accessed, but event.target will return the clicked element, and not .bermuda .

This is why in some cases you use event.stopPropagation() , so you can avoid this event propagation from child elements to parents.

    
19.02.2015 / 12:33
9

this refers to the element to which the event was attached. event.target refers to the element that triggered the event.

For example, suppose you are manipulating a table and want to get the click event in a td .

<table>
    <tr>
        <td id="teste">
            <img src="testando.png" />
        </td>
    </tr>
</table>

$("#teste").on("click", function(event) {
    console.log(this);
    console.log(event.target);
});

In this example, if the user clicks the image , the event.target refers to the image and the this refers to td#teste .

    
19.02.2015 / 12:37