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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With