Difference between `this` and `e.target` upon a event listener in JS (using jquery)
Dimitrios Desyllas

Dimitrios Desyllas @pcmagas

About: Greedings I am Dimitrios Desyllas aka pc_magas. I am a php software engineer. I am interested in privacy enhancing technologies, cryptography and reverse engineering.

Location:
Acharnes, Greece
Joined:
Aug 29, 2019

Difference between `this` and `e.target` upon a event listener in JS (using jquery)

Publish Date: May 24 '24
0 2

Whilst developing in JS I had this case:



<a href="target" class="btn-toggle-form"><i class="fa fa-pencil"></i></a>


Enter fullscreen mode Exit fullscreen mode

And I made an event listener for it using jquery:



 $(".btn-toggle-form").on('click',function (e){
        e.preventDefault();
        const target = e.target;
        console.log(target)
 });


Enter fullscreen mode Exit fullscreen mode

But I noticed in my console that the target is the:



<i class="fa fa-pencil"></i>


Enter fullscreen mode Exit fullscreen mode

Instead of the link!? But using this piece of code:



$(".btn-toggle-form").on('click',function (e){
        e.preventDefault();
        const target = e.target;
        console.log(this)
 });


Enter fullscreen mode Exit fullscreen mode

Logs into a instead.

The reason why it happens

The reason why it did happen is because the i element has triggered the event. This event has been propagated till the btn-toggle-form receives it. A easy to remember diagram is:

Image description

Creative analogy

If it still confuses you, treat the link as a catgirl's ear and the event target as her sempai. The click event is the sempai pinching the catgirls' ear. The this points to the catgirl, because is the final receipient of the pinching (clicking) event e. The e.target is the sempai because is the one pinched the catgirl's ear.

(Hm,don't get the wrong idea. I didn't wrote this article just to mention catgirl. baka)

Comments 2 total

  • Samuel Rouse
    Samuel RouseMay 24, 2024

    Events also have a currentTarget property, which matches this in the jQuery event handler. This is frequently used in place of target to avoid having to deal with propagation, but there are times it can be useful to know the "source" element.

    • Dimitrios Desyllas
      Dimitrios DesyllasMay 25, 2024

      #tsundereservice
      Tsun, don't get the wrong idea, its not that I wanted to tell me. Baka

      (I am joking 10q)

Add comment