I am dealing with a javascript datatable with clickable rows. Each row when clicked forwards the browser to a different page. A column of the row contains a hyperlink. When the hyperlin is clicked I don't want the row click event to be fired or managed.
Here is how I have implemented the row click event
$(tableId+' tbody').on( 'click', 'tr', function (e) {
window.location.href = $(this).attr('url');
});
When you add an event listener to a parent, the event by default "bubbles" downwards and attaches the event to all children. So in this case you setting the event on tr
(parent) and the event will bubble down and attach itself to the td
(children). So one of these td
from what I understand contains your href
(hyperlink) and so to block the click
event which originally was set on the parent, you have to set another event listener specifically of the event type click
within the function for this event you simply need state event.stopPropagation()
and it will override the tr
click event which bubbled down.
document.addEventListener('DOMContentLoaded',()=>{
//SET EVENT ON PARENT(TR), EVENT BUBBLES BY DEFAULT DOWNWARDS THEREFORE TD's WILL INHERIT
document.getElementById('parent').addEventListener('click',()=>window.location.href = "wherever");
//ADDING ANOTHER EVENT LISTENER OF THE SAME TYPE (CLICK) WHICH BLOCKS THE BUBBLING PROPOGATION DOWNARDS
document.getElementById('myhyperlink').addEventListener('click',(e)=>event.stopPropagation());
});
If you want to prevent clicking on anchor from redirecting a page, you have to simply catch the click event and disable it's default behaviour.
$("table td a").click(function(e){
e.preventDefault();
});
You have to just prevent default behaviour, if you would also stop propagation of event, your other event listener wouldn't get called. See more info here: What's the difference between event.stopPropagation and event.preventDefault?
If your goal is to disable redirect of anchor links only when the javascript is enabled, another solution might be to set onclick
attribute that would disable default redirect. However, this seems not to work in webkit based browsers.
<a href="http://example.com" onclick="javascript:return false;">and example</a>
Here is jsFiddle with example
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