I saw many sites about this difference but no one explain in simple way. I have tried to explain this article so simple with very good example.
target vs currentTarget
event.target return the DOM element that started the event where as event.currentTarget return that element where event was attached.In given example if you click on button it will return "button" as target and "div" as currentTarget but if you click on div it will return "div" for both.
I have attached click event with "div" not any event with button. Because of event bubbling when you fired any event of a element then automatic it fired event of its parent element.
When we are clicking on button it also fired event of "div", in this case "button" will be target element and "div" will be currentTarget but when click on "div" then "div" will be target as well as currentTarget element. So only in event bubbling case target and currentTarget element will be different.
To know more about event bubbling, click here.
<!DOCTYPE html> <html> <head> <title>target vs currenTtarget in javascript</title> <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $('div.container').click(function (e) { alert(e.target.nodeName); alert(e.currentTarget.nodeName); }); }); </script> </head> <body> <div class="container" style="border:1px solid Red; width:200px;height:100px;padding:10px;"> You can also click here.<br/><br/> <button>Click Me</button> </div> </body> </html>
Thaank you for writing this
ReplyDelete