What is the difference between $(this) and $(Event.target)?

Asked

Viewed 558 times

25

Well, a question arose while I was dealing with jQuery and the code worked perfectly in Chrome using the event $(event.target), already in Firefox only worked with $(this), then arose this doubt. 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);    
});

2 answers

16


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

Already the $(event.target) can be either the element where the event is assigned or the child of that 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 some child element, such as a <p> or a <img/>, by clicking on them, the .bermuda will be accessed, however event.target return the clicked element, and not .bermuda.

That’s why in some cases you use event.stopPropagation(), to avoid this propagation of the event of the child elements for parents.

  • 1

    Thank you, very enlightening reply...

9

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

For example, suppose you’re manipulating a table and want to catch the event click 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 image, the event.target refers to the image and the this refers to td#teste.

  • Thank you, very enlightening reply...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.