javascript – What is the difference between $(this) and $(event.target)?

Question:

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

Answer:

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

On the other hand, $(event.target) can be either the element where the event is assigned or the child of the 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 a <p> or an <img/> , when you click on them, the .bermuda event will be called, but event.target return the clicked element, not .bermuda .

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

Scroll to Top