Sindico Sindico - 6 months ago 41
Javascript Question

DataTable How to prevent row click in columns containing hyperlinks

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');
});

Answer

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());
});