ElenaDBA ElenaDBA - 3 months ago 19
HTML Question

Cancelling javascript onClick event on condition

I have an html table with multiple columns, one of them is a button. When table row clicked the javascript function is called to modify

windows.href
property, in order to go to another page. When button is clicked, I want the user to stay on the same page and perform different action. I use
onClick
event of the button to do that. The function is called but the user still gets transferred to another page. How can I prevent that, other then moving
onClick
even of the table row to each table cell except the cell where button is located? is there a more elegant solution?

Answer

You're looking for stopPropagation(). In your event handler, try something like this:

function handleButtonClick(e) {
  // Stop click event from "bubbling up" to parent elements
  e.stopPropagation();

  // Other logic ...
}

For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation.

Comments