1

I have a single page app, for which I'd want to make sure link clicks don't get processed in the regular way, but are passed to my router instead. I therefore have the currently perfectly working menu code (where goto changes the HTML and returns false):

<a class="nav-link" href="/framework" onclick="return goto(this);">Home</a>
<a class="nav-link" href="/framework/register" onclick="return goto(this);">Register</a>
<a class="nav-link" href="/framework/login" onclick="return goto(this);">Log In</a>

Since every link gets the same onclick attribute anyway, is there some way I can write my links as

<a class="nav-link" href="/framework">Home</a>
<a class="nav-link" href="/framework/register">Register</a>
<a class="nav-link" href="/framework/login">Log In</a>

like I would on a non-SPA website, and have the onclick event be applied globally?

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
user1111929
  • 6,050
  • 9
  • 43
  • 73
  • My earlier statement was wrong, `$('a').onclick('return goto(this);');` does work, so that makes this quite a silly questions, apologies! – user1111929 Jan 03 '21 at 15:40

2 Answers2

2

You can attach a click event listener.

$('a').click(function(e){
   goto(this);
   e.preventDefault();//don't navigate away
   /*we can't use return goto(this) because returning false in a jQuery event handler 
      also stops event propagation */
});

If your anchor elements are dynamic, you can use event delegation.

$(document).on('click', 'a', function(e){
   goto(this);
   e.preventDefault();//don't navigate away
});
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • What do you mean by "we can't use return goto(this) because returning false in a jQuery event handler also stops event propagation"? That's interesting, I was not aware this could yield any problems. – user1111929 Jan 03 '21 at 15:42
  • @user1111929 `return false` in a jQuery event handler is equivalent to `e.preventDefault(); e.stopPropagation();` – Unmitigated Jan 03 '21 at 15:43
  • @user1111929 See also: https://stackoverflow.com/questions/5927689/when-should-i-use-return-false-in-jquery-function – Unmitigated Jan 03 '21 at 15:43
  • That is really interesting, and I was doing it wrong on form submits as well, so this has been valuable to me. Thanks! – user1111929 Jan 03 '21 at 15:59
-1

Maybe this?

element.addEventListener('click', function(e) {
  e.preventDefault()

  // Do your things
})
Zeriz
  • 1
  • 1
  • `e` is not an *Event Binder* - it's an Object argument provided by the `addEventListener` method. It's not *bound* to anything. – Roko C. Buljan Jan 03 '21 at 15:37