Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the real clicked element tag name for once with jquery

Tags:

jquery

click

I want my click function to run for all elements and in that i wanna get the clicked element tag name.

For a page like this for example,

<html>
<body>
  <form>
   <div>
     <input type="text">
     <textarea></textarea>
   </div>
  </form>
</body>
</html>

if i run this js code

$("*").live('click',function(evt) {
    alert(evt.target.tagName);      
});

and click on the textarea, it alerts "TEXTAREA" for 5 times because it has 4 parents.

Where to fix?

like image 604
Batu.Khan Avatar asked Dec 12 '25 03:12

Batu.Khan


1 Answers

Use jQuery's stopPropagation() method:

$("*").live('click',function(evt) {
    evt.stopPropagation();
    alert(evt.target.tagName);      
})

JSFiddle demo.

like image 170
James Donnelly Avatar answered Dec 14 '25 01:12

James Donnelly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!