[jquery] Difference between $(this) and event.target?

I'm new to jQuery, and was making tabbed panels, following the tutorial in JavaScript and jQuery : The Missing Manual, there's that first line when the author does this :

   var target = $(this);

But I tried to do it that way

   var target = evt.target;

and I got that error :

Uncaught TypeError: Object http://localhost/tabbedPanels/#panel1 has no method 'attr'

And when I changed evt.target back to $(this), it worked like a charm.

I want to know what's the difference between $(this) and evt.target ?

Here's my code in case you needed it :

index.html :

<!DOCTYPE html>
<html>
    <head>
        <title>Tabbed Panel</title>
        <style>
            body {
               width : 100%;
               height: 100%;
            }
            
            #wrapper {
                margin : auto;
                width : 800px;                
            }
            
            #tabsContainer {
                overflow: hidden;
            }
            
            #tabs {                
                padding:0;
                margin:0;
            }                
            
            #tabs li {
                float : left;
                list-style:none;
            }
            
            #tabs a {
                text-decoration:none;
                padding : 3px 5px;                
                display : block;                
            }
            
            #tabs a.active {
                background-color : grey;                
            }            
            #panelsContainer {
                clear: left;
            }            
            #panel1 {
                color : blue;
            }            
            #panel2 {
                color : yellow;
            }
            #panel3 {
                color: green;
            }
            #panel4 {
                color : black;
            }         
            
        </style>
        <script type="text/javascript" src="jquery-1.8.0.min.js"></script>
        <script type="text/javascript" src="script.js"></script>        
    </head>
    
    <body>
        <div id="wrapper">
            <div id="tabsContainer">
                <ul id="tabs">
                    <li><a href="#panel1">Panel1</a></li>
                    <li><a href="#panel2">Panel2</a></li>
                    <li><a href="#panel3">Panel3</a></li>
                    <li><a href="#panel4">Panel4</a></li>
                </ul>
            </div>
            <div id="panelsContainer">
                <div id="panel1" class="panel">
                    this is panel1
                </div>
                <div id="panel2" class="panel">
                    this is panel2
                </div>
                <div id="panel3" class="panel">
                    this is panel3
                </div>
                <div id="panel4" class="panel">
                    this is panel4
                </div>                
            </div>
        </div>
        
    </body>
    
</html>

script.js :

$(function(){
    $("#tabs a").click(function(evt){
       var target = evt.target,
           targetPanel = target.attr("href");
       $(".panel").hide();
       $("#tabs a.active").removeClass("active");
       target.addClass("active").blur();
       $(targetPanel).fadeIn(300);
       evt.preventDefault();
    });
    
    $("#tabs a:first").click();
})

This question is related to jquery this jquery-events

The answer is


There is a difference between $(this) and event.target, and quite a significant one. While this (or event.currentTarget, see below) always refers to the DOM element the listener was attached to, event.target is the actual DOM element that was clicked. Remember that due to event bubbling, if you have

<div class="outer">
  <div class="inner"></div>
</div>

and attach click listener to the outer div

$('.outer').click( handler );

then the handler will be invoked when you click inside the outer div as well as the inner one (unless you have other code that handles the event on the inner div and stops propagation).

In this example, when you click inside the inner div, then in the handler:

  • this refers to the .outer DOM element (because that's the object to which the handler was attached)
  • event.currentTarget also refers to the .outer element (because that's the current target element handling the event)
  • event.target refers to the .inner element (this gives you the element where the event originated)

The jQuery wrapper $(this) only wraps the DOM element in a jQuery object so you can call jQuery functions on it. You can do the same with $(event.target).

Also note that if you rebind the context of this (e.g. if you use Backbone it's done automatically), it will point to something else. You can always get the actual DOM element from event.currentTarget.


There is a significant different in how jQuery handles the this variable with a "on" method

$("outer DOM element").on('click',"inner DOM element",function(){
  $(this) // refers to the "inner DOM element"
})

If you compare this with :-

$("outer DOM element").click(function(){
  $(this) // refers to the "outer DOM element"
})

'this' refers to the DOM object to which the event listener has been attached. 'event.target' refers to the DOM object for which the event listener got triggered. A natural question arises as, why the event listener is triggering for other DOM objects. This is because event listener attached parent triggers for child object too.


this is a reference for the DOM element for which the event is being handled (the current target). event.target refers to the element which initiated the event. They were the same in this case, and can often be, but they aren't necessarily always so.

You can get a good sense of this by reviewing the jQuery event docs, but in summary:

event.currentTarget

The current DOM element within the event bubbling phase.

event.delegateTarget

The element where the currently-called jQuery event handler was attached.

event.relatedTarget

The other DOM element involved in the event, if any.

event.target

The DOM element that initiated the event.

To get the desired functionality using jQuery, you must wrap it in a jQuery object using either: $(this) or $(evt.target).

The .attr() method only works on a jQuery object, not on a DOM element. $(evt.target).attr('href') or simply evt.target.href will give you what you want.


Within an event handler function or object method, one way to access the properties of "the containing element" is to use the special this keyword. The this keyword represents the owner of the function or method currently being processed. So:

  • For a global function, this represents the window.

  • For an object method, this represents the object instance.

  • And in an event handler, this represents the element that received the event.

For example:

<!DOCTYPE html>
<html>
    <head>
        <script>
        function mouseDown() {
            alert(this);
        }
        </script>
    </head>
    <body>
        <p onmouseup="mouseDown();alert(this);">Hi</p>
    </body>
</html>

The content of alert windows after rendering this html respectively are:

object Window
object HTMLParagraphElement

An Event object is associated with all events. It has properties that provide information "about the event", such as the location of a mouse click in the web page.

For example:

<!DOCTYPE html>
<html>
    <head>
        <script>
        function mouseDown(event) {
            var theEvent = event ? event : window.event;
            var locString = "X = " + theEvent.screenX + " Y = " + theEvent.screenY;
            alert(event);
                    alert(locString);
        }
        </script>
    </head>
    <body>
        <p onmouseup="mouseDown(event);">Hi</p>
    </body>
</html>

The content of alert windows after rendering this html respectively are:

object MouseEvent
X = 982 Y = 329

There are cross browser issues here.

A typical non-jQuery event handler would be something like this :

function doSomething(evt) {
    evt = evt || window.event;
    var target = evt.target || evt.srcElement;
    if (target.nodeType == 3) // defeat Safari bug
        target = target.parentNode;
    //do stuff here
}

jQuery normalises evt and makes the target available as this in event handlers, so a typical jQuery event handler would be something like this :

function doSomething(evt) {
    var $target = $(this);
    //do stuff here
}

A hybrid event handler which uses jQuery's normalised evt and a POJS target would be something like this :

function doSomething(evt) {
    var target = evt.target || evt.srcElement;
    if (target.nodeType == 3) // defeat Safari bug
        target = target.parentNode;
    //do stuff here
}

http://api.jquery.com/on/ states:

When jQuery calls a handler, the this keyword is a reference to the element where the event is being delivered; for directly bound events this is the element where the event was attached and for delegated events this is an element matching selector. (Note that this may not be equal to event.target if the event has bubbled from a descendant element.)

To create a jQuery object from the element so that it can be used with jQuery methods, use $( this ).

If we have

<input type="button" class="btn" value ="btn1">
<input type="button" class="btn" value ="btn2">
<input type="button" class="btn" value ="btn3">

<div id="outer">
    <input type="button"  value ="OuterB" id ="OuterB">
    <div id="inner">
        <input type="button" class="btn" value ="InnerB" id ="InnerB">
    </div>
</div>

Check the below output:

<script>
    $(function(){
        $(".btn").on("click",function(event){
            console.log($(this));
            console.log($(event.currentTarget));
            console.log($(event.target));
        });


        $("#outer").on("click",function(event){
            console.log($(this));
            console.log($(event.currentTarget));
            console.log($(event.target));
        })
    })
</script>

Note that I use $ to wrap the dom element in order to create a jQuery object, which is how we always do.

You would find that for the first case, this ,event.currentTarget,event.target are all referenced to the same element.

While in the second case, when the event delegate to some wrapped element are triggered, event.target would be referenced to the triggered element, while this and event.currentTarget are referenced to where the event is delivered.

For this and event.currentTarget, they are exactly the same thing according to http://api.jquery.com/event.currenttarget/


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to this

this in equals method React: "this" is undefined inside a component function How to access the correct `this` inside a callback? jQuery $(this) keyword Difference between $(this) and event.target? 'this' vs $scope in AngularJS controllers Difference between getContext() , getApplicationContext() , getBaseContext() and "this" Use of "this" keyword in C++ What is context in _.each(list, iterator, [context])? What does 'var that = this;' mean in JavaScript?

Examples related to jquery-events

Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function Detect Close windows event by jQuery How to bind Events on Ajax loaded Content? Get clicked element using jQuery on event? jQuery click events firing multiple times jQuery.click() vs onClick Bootstrap onClick button event Difference between $(this) and event.target? Getting the class of the element that fired an event using JQuery Attaching click event to a JQuery object not yet added to the DOM