Suppose you have a table, for example to show users, and you want the table row to be clickable. If you click the row, you will go to a page that shows user information. Or maybe edit the user. But the last column of your row also has some action buttons that can delete the user, de-activate it, or whatever. So, for example, something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<table id="userList"> <thead> <tr> <th>ID</th> <th>Username</th> <th>Email</th> <th></th> </tr> </thead> <tbody> <tr data-item-url="/user/1/show"> <td>1</td> <td>admin</td> <td>darklord@foobar.com</td> <td> <a href="/user/1/del"><i class="fa fa-times"></a> <a href="/user/1/deactivate"><i class="fa fa-pause"></a> </td> </tr> </tbody> </table> |
Now, if you add a click event on the tr, when you click the button, both the button and click event will fire. To prevent this, I found this nice stackoverflow post about it. This answer suited my needs better, because I also had used font awesome icons for my anchors.
I did change it a bit however, because you already know the tr element when it’s being clicked on, right? So I ended up with this javascript code, and it seems to work.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<script> jQuery(document).ready(function() { $('#userList tr').on('click', function(event) { var jqTarget = $(event.target); if (jqTarget.closest('a', this).length > 0) return true; event.preventDefault(); location.href = $(this).data('item-url'); }); }); </script> |
So actually the credits go to Augusto, but I just wanted to make a note her, in case I ever forget. The tagline my external memory is for real you know. My internal memory is not always that reliable ;-)