Ali
Ali

Reputation: 2768

Prevent Hyperlink to trigger Jquery?

I wrote this script so that if a user clicks on any <TR>, it gets highlighted - this is working fine and it highlights the TR fine.

<script>
    $(document).ready(function () {
        $(document).on('click', 'tbody tr', function (e) {
            e.stopPropagation();        
            $(this).toggleClass('selected');         

        });        
    });
</script>

Now the issue is my <tr> has a hyperlink inside it and when user clicks on that hyper before the redirect the <tr> gets highlighted

<tr>   
  <td >
   <div class="header">
    <a href="http://google.com">TITLE HERE</a>
   </div>
  </td>
</tr>

How to prevent that happening

Cheers

        $(document).ready(function () {
            $(document).on('click', 'tbody tr', function (e) {
                e.stopPropagation();        
                $(this).toggleClass('selected');         
    
            });        
        });
.selected {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<table class="table table-hover">
        <thead>
            <tr>
              Link
            </tr>
        </thead>
    <tbody id="trow">
        <tr>   
      <td style="Width:500px" >
       <div class="header">
        <a href="http://google.com">TITLE HERE</a>
       </div>
      </td>
    </tr>
    </tbody>

Upvotes: 0

Views: 187

Answers (2)

31piy
31piy

Reputation: 23859

You need to listen to the click of a and stop the propagation in order to prevent highlighting of the row:

$(document).ready(function() {

  $("table").on('click', 'tbody tr a', function(e) {
    event.stopPropagation();
  });

  $(document).on('click', 'tbody tr', function(e) {
    $(this).toggleClass('selected');
  });


});
.selected {
  background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
  <tbody>
    <tr style="height: 100px;">
      <td>
        <div class="header">
          <a href="https://google.com">TITLE HERE</a>
        </div>
      </td>
    </tr>
  </tbody>
</table>

Upvotes: 1

First change 'tbody tr' to 'tbody tr a'

Second then to set the class on the tr use .closest() as in $(this).closest("tr").toggleClass('selected')

Demo

$(document).ready(function() {
  $(document).on('click', 'tbody tr', function(e) {
    if (e.target.nodeName == "A") {
      e.stopPropagation();
    } else {
      $(this).closest("tr").toggleClass('selected');
    }
  });
});
.selected {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-hover">
  <thead>
    <tr>
      Link
    </tr>
  </thead>
  <tbody id="trow">
    <tr>
      <td style="Width:500px">
        <div class="header">
          <a href="http://google.com">TITLE HERE</a>
        </div>
      </td>
    </tr>
  </tbody>

Upvotes: 2

Related Questions