0

This should be a simple one, but I haven't been able to find an answer

I have a link that triggers a function.

<a href="someplace.html" onclick="myfunction()"</a>

If I want to prevent the link from opening, I need the function to return false, right?

function myfunction() {
  // some code
  return false;
}

However, this doesn't work. I might be missing something essential here, but please help me out.

Why is this not working: http://codepen.io/lukastillmann/pen/aNmZbx?editors=1010

lukastillmann
  • 419
  • 1
  • 3
  • 11

1 Answers1

3

You have to return false from the event handler function.

Your event handler function:

  1. calls myfunction()
  2. … and that's it, it has no return statement.

myfunction has a return statement, but it isn't the event handler function. It is another function called from the event handler function.

onclick="return myfunction()"

Modern code wouldn't use onclick attributes which have horrible gotchas and violate several best practices.

function myfunction(e) {
  // some code
  e.preventDefault();
}

document.querySelector("a").addEventListener("click", myfunction);
Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I did not know that gotcha about `onclick`. – Andy Mar 14 '16 at 16:59
  • It's also worth noting that if there's an uncaught error in the JavaScript function it'll effectively fall through and jump to the link. – Hugo Yates Mar 14 '16 at 16:59
  • "return myfunction()" does the trick. Thank you! I had actually tried using the event listener and e.preventDefault: http://codepen.io/lukastillmann/pen/oxzrVL?editors=1010 But this is still not working. Any Ideas? – lukastillmann Mar 14 '16 at 17:05
  • @lukastillmann — `preventDefault` is a function. You have to call it, not just mention it. You lost the `()`. – Quentin Mar 14 '16 at 17:10
  • thanks @Quentin and everyone. Somehow this has been driving me nuts for days. – lukastillmann Mar 14 '16 at 17:20