1

I have a link with a href and onClick function.

<a href={menuItem.url}  onClick={e => {
 var checkedItems = document.querySelectorAll("input:checked") as NodeListOf<HTMLInputElement>;
      for (let i = 0; checkedItems[i]; i++) {
        checkedItems[i].checked = false;
      }
 window.location.href = menuItem.url;  }}>

I want the href link the be there so users can see the url when hovering, but I want only the onclick to be executed. I have tried

e.stopPropagation();
e.preventDefault();
e.nativeEvent.stopImmediatePropagation();
return false;

But none of those seem to work.

Velatha
  • 29
  • 1
  • 8
  • A similar question was asked with [here](https://stackoverflow.com/questions/15622100/how-can-i-disable-href-if-onclick-is-executed). Try having your `onclick` function handler return `false`. – Neill Herbst Feb 28 '19 at 09:01
  • I have also tried that, doesn't seem to be working. I've put logs in the onClick and it doesn't get executed – Velatha Feb 28 '19 at 09:07

1 Answers1

1

One solution would be to add a new "internal element" such as a <span> inside of the <a> element, and bind the onClick event handler with event.stopPropagation() to that internal element.

This would cause the <span> to intercept and stop the propagation of the click event before it bubbles up to the parent <a> (which would by default cause the browser to navigate to the href url).

You should find this method still preserves visibility of the url assigned to the href attribute of <a> for the user when it is hovered with the mouse cursor:

<a href={menuItem.url}>
    <span onClick={e => {

        // Intercepts and prevents the event from propagating up to the parent <a>
        e.stopPropagation();

        // Your existing logic for the onClick event
        var checkedItems = document.querySelectorAll("input:checked") as NodeListOf<HTMLInputElement>;

        for (let i = 0; checkedItems[i]; i++) {
            checkedItems[i].checked = false;
        }

        window.location.href = menuItem.url;

    }}> The text label for your link </span>
</a>

For this method to work, it assumed that there is no padding between the box border (outer boundary) of the <a> and the box border of the inner <span>. Here's a jsFiddle (non-jsx) demonstrating the general idea.

Hope that helps!

Dacre Denny
  • 29,664
  • 5
  • 45
  • 65