I am having an issue where a table row has a click event, but when a user clicks a link in one of the table row's cells I do not want the row's click event to fire.
Imagine a case where a table cell has a link within it and normally clicking the empty areas of any of the table rows (e.g. not links) causes some action like an accordion/row collapse and expand.
What is occurring is that the click event below is firing then the link is followed (the intended action).
What I need to happen is to exclude clicking the a href's within a from triggering the tr.title-row click action (e.g. the alert should not fire and the link should be followed).
This jQuery code is setting up click events for the title row (e.g. all the TH's in that row, any cells, etc.)
$(document).ready(function() {
$(".report tr.title-row").click(function() {
alert('I am firing!');
});
Here is the same HTML this applies to:
<table width="100%" cellspacing="0" cellpadding="0" border="0" class="report">
<tbody>
<tr class="title-row">
<th width="340"><span class="title">Test</span>
</th>
<th width="130" class="center-cell">Test</th>
<th width="90" class="status"></th>
<th></th>
<th width="160"> <a target="_self" href="http://www.google.com" class="link-class sub-class">I am triggering the TR click event</a>
</th>
</tr>
<tr>
<td class="sub-row" colspan="5">
<table width="100%" cellspacing="0" cellpadding="0" border="0">
<tbody>
<tr>
<td><strong>SubRow</strong>
</td>
<td width="90" class="status"><span class="sub">Sub</span>
</td>
<td width="120"></td>
<td width="160"><a title="Continue" href="http://www.yahoo.com">Something</a>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
Can check the target
of the row click and only run code if target isn't an <a>
tag:
$(".report tr.title-row").click(function(event) {
if( ! $(event.target).is('a') ){
alert('I only fire when A not clicked!');
}
});
just stop bubbling the event to the row
$(".report tr.title-row").click(function() {
alert('I am firing!');
});
$(".report tr.title-row a").click(function(ev){
// link clicked
// so something
ev.stopPropagation(); // stop triggering the event to the table row
});
btw... for better code just use on
instead of the named eventhandler
$(".report tr.title-row").on( 'click', function() {
alert('I am firing!');
});
$(".report tr.title-row a").( 'click', function(ev){
// link clicked
// so something
ev.stopPropagation(); // stop triggering the event to the table row
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With