Best way to create an <a> link with empty href
JavascriptJqueryCssHtmlJavascript Problem Overview
I want to create a link , and to force the link anchor using javaScript, i tried the following:-
<a id="ServerSort" href="#" style="text-decoration:underline">
it worked well but the page will loose its current position after clicking on the <a>
link.
I need the link to have an href, because i need need the mouse to change the cursor when going over it ?
can anyone advice ?
Javascript Solutions
Solution 1 - Javascript
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;
});
Solution 2 - Javascript
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.
Solution 3 - Javascript
.clickable {
cursor: pointer;
}
<a id="ServerSort" class="clickable">Foo</a>
Solution 4 - Javascript
> 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()
or stopImmediatePropagation()
, 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.
Solution 5 - Javascript
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