Why event.target gives multiple results?

1.4k views Asked by At

I have a 3*3 table. When I click on td element in my console log td is printed six times and I want it to print out just once. Why is this happening and how to prevent it?

JS:

$("*").click(function(event){
  console.log(event.target);//is this here executing 6 times, why...
});

HTML:

<table>
    <tr>
        <td>Content</td>
        <td>Content</td>
        <td>Content</td>
    </tr>
    <tr>
        <td>Content</td>
        <td>Content</td>
        <td>Content</td>
    </tr>
    <tr>
        <td>Content</td>
        <td>Content</td>
        <td>Content</td>
    </tr>
</table>
3

There are 3 answers

4
AmmarCSE On BEST ANSWER

This is happening because of propagation. Since you used $('*') it attached the click handler seperately to each element. Therefore, when you clicked on td, the event bubbled up to parent element handlers.

To see the difference, try

$("td").click(function(event){
  console.log(event.target);//will only log once since it was only attached to td
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<table>
    <tr>
        <td>Content</td>
        <td>Content</td>
        <td>Content</td>
    </tr>
    <tr>
        <td>Content</td>
        <td>Content</td>
        <td>Content</td>
    </tr>
    <tr>
        <td>Content</td>
        <td>Content</td>
        <td>Content</td>
    </tr>
</table>

or stop propagation

$("*").click(function(event){
  event.stopPropagation();
  console.log(event.target);//will only log once since propagation was stopped above
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<table>
    <tr>
        <td>Content</td>
        <td>Content</td>
        <td>Content</td>
    </tr>
    <tr>
        <td>Content</td>
        <td>Content</td>
        <td>Content</td>
    </tr>
    <tr>
        <td>Content</td>
        <td>Content</td>
        <td>Content</td>
    </tr>
</table>

1
taxicala On

you are selecting * in your jquery, that means that each and every element in your DOM will be selected by that query. Now, in jQuery the events bubble up the DOM untill the document or body. If you click an element that has 5 grandparents, the event will be executed once for the clicked element, and once for each of the elements parents and so on untill reaching the body. If you dont want this to happen, you should add event.stopPropagation.

$("*").click(function(event){
  event.stopPropagation();
  console.log(event.target);//is this here executing 6 times, why...
});
6
Michelangelo On

This will also help: http://jsfiddle.net/wek58fk4/1/

$("*").click(function(event){
  console.log(event.target);//is this here executing 6 times, why...
  return false;
});