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


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

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

2 answers


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:

    console.log(e.target); // #teste
    console.log(this); // #document

HTML example:

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

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

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 .

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

$("#teste").on("click", function(event) {

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