Search code examples
javascriptjqueryhtmljquery-click-event

Table tr and td have weird click events


I have a table like the following snippet shows.

$(function(){
  $('.table-price td.go-to-price').click(function(){
    console.log($(this).attr('data-link'));
    goToLink($(this).attr('data-link'));
  })

  $('.table-price tr.go-to-product').click(function(){
    console.log($(this).attr('data-link'));
    goToLink($(this).attr('data-link'));
  })
})


function goToLink(url) {
  location.href = url ;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table-price">
  <tr class="go-to-product" data-link="http://tahrircenter.com/product/correction-pens/url">
      <td>1</td>
      <td>10013</td>
      <td>عنوان</td>
      <td></td>
      <td>10</td>
      <td>
          <p class="">0</p>
      </td>
      <td class="go-to-price" data-link="http://tahrircenter.com/product/correction-pens/url#price-change" >
          <a href="http://tahrircenter.com/product/correction-pens/url#price-change">IMAGE</a>
      </td>
  </tr>
</table>

The tr has a data-link attribute and the last td has a different data-link attribute, but when I click on the tr element, the website navigates to url of td element, instead of the tr element.


Solution

  • You need to stop the click event from bubbling when you click on the td using stopPropagation(), like :

    $('.table-price td.go-to-price').click(function(e){
      e.stopPropagation();
    
      console.log($(this).attr('data-link'));
      goToLink($(this).attr('data-link'));
    })
    

    Hope this helps.

    $(function(){
      $('.table-price td.go-to-price').click(function(e){
          e.stopPropagation();
          
          console.log($(this).attr('data-link'));
          goToLink($(this).attr('data-link'));
      })
    
      $('.table-price tr.go-to-product').click(function(e){
          e.stopPropagation();
    
          console.log($(this).attr('data-link'));
          goToLink($(this).attr('data-link'));
      })
    })
    
    
    function goToLink(url) {
      location.href = url ;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table class="table-price">
      <tr class="go-to-product" data-link="http://tahrircenter.com/product/correction-pens/url">
          <td>1</td>
          <td>10013</td>
          <td>عنوان</td>
          <td></td>
          <td>10</td>
          <td>
              <p class="">0</p>
          </td>
          <td class="go-to-price" data-link="http://tahrircenter.com/product/correction-pens/url#price-change" >
              <a href="http://tahrircenter.com/product/correction-pens/url#price-change">IMAGE</a>
          </td>
      </tr>
    </table>