Best way to create an <a> link with empty href [duplicate]
You can use javascript:void(0)
<a id="ServerSort" href="javascript:void(0)">
you don't need style="text-decoration:underline"
as commented by King King
by jQuery you can do it by event.preventDefault()
Stop the default action of the event .
$('#ServerSort').click(function(event){
event.preventDefault(); //or return false;
});
The best way to do that is to set the href to #0
like this:
<a href="#0">blabla</a>
Here's why: You will NEVER have anything on the page with the ID 0 (if you do, there's a problem there anyways), and since #0
doesn't exist, the click event doesn't bring you back to the top of page. You do NOT need JavaScript to do that and you should not use JavaScript.
.clickable {
cursor: pointer;
}
<a id="ServerSort" class="clickable">Foo</a>
A few options exist:
<a id="ServerSort" href="javascript:">
<a id="ServerSort" href="javascript://">
<a id="ServerSort" href="javascript:void(0)">
These are considered bad practice and I would never recommend something like this for production. I typically use the first option when linking to pages that don't exist during the development phase.
Preferably, I would not use a at all, I switch to a span in example below:
<span id="ServerSort" onclick="return false">Test Link</span>
and just style an element accordingly:
<style type="text/css">
#ServerSort {
text-decoration:underline;
}
#ServerSort:hover {
color:red;
cursor:pointer;
}
</style>
I am in-lining the js and just hand writing a here to show a different approach which avoid the need to override the default behavior.
Use Event.preventDefault()
This method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.
function clickme(ev) {
alert('You stay here!')
ev.preventDefault()
}
<a onclick='clickme(event)' href='https://www.google.com/'>https://www.google.com</a>
The event continues to propagate as usual, unless one of its event listeners calls
stopPropagation()
orstopImmediatePropagation()
, either of which terminates propagation at once.
Alternatively, you can use onclick='return false'
(either inline or in a function). It will prevent default browser behaviour (more info):
function clickme() {
alert('You stay here!');
return false;
}
<a href="https://www.google.com/" onclick='return clickme()'>https://www.google.com/</a>
This approach prevents the event to propagate, though. More details.