Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - Difference between event.target and this keyword?

What is the difference between event.target and this?

Let's say I have

$("test").click(function(e) {
    $thisEventOb = e.target;
    $this = this;
    alert($thisEventObj);
    alert($this);
});

I know the alert will pop different value. Anyone could explain the difference? Thanks a million.

like image 322
FlyingCat Avatar asked Apr 16 '10 15:04

FlyingCat


1 Answers

Crispy answer

this gives you the reference of the DOM element where the event is actually attached.

event.target gives you the reference of the DOM element where the event occurs.

Long answer

jQuery(document).ready(function(){
    jQuery(".outer").click(function(){
	   var obj = jQuery(event.target);
	   alert(obj.attr("class"));
    })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer">
        Outer div starts here
	<div class="inner">
	    Inner div starts here
	</div>
</div>

When you run the above code snippet you will see that event.target is alerting the class name of the div that is actually clicked.

However this will give the reference of the DOM object on which the click event is bind. Check the below code snippet to see how this works, always alerting the class name of the div on which the click event is bind even if you click the inner div.

jQuery(document).ready(function(){
  jQuery(".outer").click(function(){
    var obj = jQuery(this);
    alert(obj.attr("class"));
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer">
    Outer div starts here
    <div class="inner">
	    Inner div starts here
    </div>
</div>
like image 65
Abdullah Khan Avatar answered Nov 09 '22 23:11

Abdullah Khan