Skip to content
Advertisement

How to link table row to external URL with Javascript?

I my app I have a table like this:

<tr data-url="/entry/57/edit">
  <td>
    Text
  </td>
  <td>
    <a href="https://www.external.com">Link 1</a>
  </td>
  <td>
    <a href="https://www.external.com" target="_blank">Link 2</a>
  </td>
</tr>

This is my Javascript:

function TableRow() {

  const rows = document.querySelectorAll('table tr[data-url]');

  rows.forEach(row => {
    row.addEventListener('click', function(e) {
      handleClick(row, e);
    });
  });

  function handleClick(row, e) {
    let url = row.getAttribute('data-url');
    window.document.location = url;
  }

}

document.addEventListener('DOMContentLoaded', TableRow);

How come that clicking on Link 1 takes me to www.external.com (which is what I want) but clicking on Link 2 takes me to /entry/57/edit (which is not what I want)?

I want both links to take me to www.external.com. How can this be done?

Advertisement

Answer

As Pavel already pointed out you need to stop event propagation. Otherwise after openening the new tab the event still propagates to the click handler of the table row.

Adding a click listener to your anchors that will stop event propagation should fix your problem

function TableRow() {

  const rows = document.querySelectorAll('table tr[data-url]');

  rows.forEach(row => {
    row.addEventListener('click', function(e) {
      handleClick(row, e);
    });
  });

  function handleClick(row, e) {
    let url = row.getAttribute('data-url');
    window.document.location = url;
  }

  const anchors = document.querySelectorAll('table tr[data-url] a');
  anchors.forEach(anchor => {
    anchor.addEventListener('click', function(e) {
      e.stopPropagation();
    });
  });

}

document.addEventListener('DOMContentLoaded', TableRow);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement