4

In my web app, a lot of functionality is exposed as links that have onclick handlers exposing that functionality but the actual link is set to javascript void(0) like so...

<a href="javascript:void(0)" onclick="myApp.callJen(1303, this)" rel="nofollow">Call Jennifer</a>

It seems these kind of links don't play nice when my app is injected into Single Page Applications (SPAs) like Backbone.js and Angular. Sometimes clicking on this links in such sites will go to an actual page not found (not sure why that happens).

Anyhow how should I replace such links for those sites?

Let us say using real URLs or buttons is not an option at this point.

Other posts have suggested something like this..

<a href="#!">Link</a>

Or this..

// Cancel click event
$('.cancel-action').click(function(){
alert('Cancel action occurs!');
});

a { cursor: pointer; color: blue; }
a:hover,a.hover { text-decoration: underline; }
 <a class="cancel-action">Cancel this action</a>

I honestly don't like either of these, so can you suggest something better?

Community
  • 1
  • 1
AbuMariam
  • 3,282
  • 13
  • 49
  • 82

2 Answers2

9

The correct way would be to “prevent the default action“. In a jQuery event handler: event.preventDefault() or simply return false;.

Expert knowledge: Note that void is an operator and the parentheses are not required.

Fabian Klötzl
  • 407
  • 3
  • 10
  • Notice that when you remove the href from an anchor it would not be styled as an anchor tag correctly by browsers - so basically you lose the styles of the link – ehab Dec 15 '19 at 12:03
  • @ehab My answer suggest no such thing as removing the href. – Fabian Klötzl Dec 16 '19 at 13:13
  • Old answer, and since jQuery is almost obsolete at this point, I will also point out that event.preventDefault() is standard in ECMAScript (JS), so no jQuery required. Also, using the javascript: psudo-protocol, void(0) is required, so in this case it IS required to work as described. Using that isn't adviced. The best solution would be to use – Carnix Mar 17 '21 at 18:06
0

This is an old question, but turned up in a search so thought I would add my insights.

The ideal solution would be to replace all <a> elements with <button> elements, then style them as links, for example:

<button id="buttonLink" class="buttonLink" style="background: none;border: none; padding: 0; color: #069; text-decoration: underline; cursor: pointer;">LINK TEXT HERE</button>

I wouldn't recommend using the inline style like that, so you'd want to move that to a stylesheet, but that's the minimum CSS you'd need. Then you would attach click events (you should not use onclick if you can help it, but rather addEventListner in your script, but that's a whole other topic) to have it execute your functionality.

Carnix
  • 543
  • 6
  • 14