A row in a table where each first cell contains a link needs to be clicked and open a url.
<table>
<tr>
<td><a class="fancybox" href="detail.aspx?CID=67525">LT5C260A436C41</a></td>
<td>more data</td>
</tr>
<tr>
<td><a class="fancybox" href="detail.aspx?CID=17522">LA5C260D436C41</a></td>
<td>more data</td>
</tr>
...
</table>
The complete row should be clickable instead of only the link top open the detail page in a fancybox, ie in the page itself.
So I tried to do something like this:
$("table tr").bind('click',function(e) {
e.stopPropagation();
$(this).find("a").trigger('click');
});
But it seems that the event is bubbling recursivly resulting in a:
Uncaught RangeError: Maximum call stack size exceeded
How can I trigger the click on the full row instead of only the link in a proper way avoiding the stackoverflow?
UPDATE: I really appreciate the answers below, but my question is about triggering the event, NOT executing the behaviour inside that event. Workarounds could be nice, but not in this case.
The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.
If you want native JS to trigger click event without clicking then use the element id and click() method of JavaScript.
To only trigger parent click event when a child is clicked with JavaScript, we call stopPropagation . parent. addEventListener( "click", (e) => { e. stopPropagation(); console.
This worked well:
$("table tr").click(function(e) {
var $link = $(this).find("a");
if (e.target === $link[0]) return false;
$link.trigger('click');
return false;
});
EDIT:
Why most solutions don't work — they fail, because when the link was clicked, the immediate handler attached runs. The event then bubbles to see if a handler was attached to a table cell, row, etc.
When you suggest triggering a click you cause the recursion: the link was clicked → fancybox → bubbles → aha! table row → trigger the link click → the link was clicked…
When you suggest to stop propagation, please note that event stops bubbling to parent elements, so a click
handler attached to body
will not be executed.
Why the code above works — we check if the event bubbled from a link. If true, we simply return and stop further propagation.
See the updated fiddle: http://jsfiddle.net/F5aMb/28/
try
$('table tr').click(function() {
var href = $(this).find("a").attr("href");
if(href) {
window.location = href;
}
});
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