300

I have seen the following href used in webpages from time to time. However, I don't understand what this is trying to do or the technique. Can someone elaborate please?

<a href="javascript:;"></a>
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
John Livermore
  • 30,235
  • 44
  • 126
  • 216
  • 2
    You can call a JS method with this if im not mistaken.. javascript:SomeFunction() – Rob Oct 13 '11 at 13:47
  • 2
    It's not trying to do anything which can't better be handled with a proper click handler. You should avoid this because it's ugly, inaccessible and has caused people to use the `javascript:` scheme where it shouldn't be used (`onclick="javascript:…"`) – Gareth Oct 13 '11 at 13:51
  • 2
    Check this out: http://stackoverflow.com/a/138233/908879 – ajax333221 Dec 13 '11 at 18:57

12 Answers12

318

An <a> element is invalid HTML unless it has either an href or name attribute.

If you want it to render correctly as a link (ie underlined, hand pointer, etc), then it will only do so if it has a href attribute.

Code like this is therefore sometimes used as a way of making a link, but without having to provide an actual URL in the href attribute. The developer obviously wanted the link itself not to do anything, and this was the easiest way he knew.

He probably has some javascript event code elsewhere which is triggered when the link is clicked, and that will be what he wants to actually happen, but he wants it to look like a normal <a> tag link.

Some developers use href='#' for the same purpose, but this causes the browser to jump to the top of the page, which may not be wanted. And he couldn't simply leave the href blank, because href='' is a link back to the current page (ie it causes a page refresh).

There are ways around these things. Using an empty bit of Javascript code in the href is one of them, and although it isn't the best solution, it does work.

Spudley
  • 166,037
  • 39
  • 233
  • 307
  • 18
    Out of curiosity, is there a better way to do this ? – Rahman Kalfane Oct 13 '11 at 13:58
  • 34
    a better was of doing this is if the event function does `return false;` or `event.preventDefault()` then the `href` action will never be called, so you can put something more sensible in there. – Spudley Oct 13 '11 at 14:03
  • 7
  • Also href="#" can cause problems if you are working in an enterprise environment where every single url is checked and blocked if it contains strange elements (such as # in my case). E.g. doing an ajax call from a URL that has "#" at the end which triggers our firewall and prevents the ajax call from functioning correctly. Real pain in the ass... – reaper_unique Jun 26 '13 at 16:05
  • @reaper_unique: really? I would say that your firewall is badly configured. `#` is a standard part of how URLs work. At the basic level, it's a link to another part of the same page; click on `#foo` and the page will jump to the section labelled `foo`. It was designed for things like a table of contents. Nothing sinister about that. The usage described in this question is poor practice but no security risk. Today `#` is often used by pages that load data via ajax so they can provide permanent links into their sites. And that's not suspicious either. Your firewall needs to lighten up a bit. – Spudley Jun 27 '13 at 13:52
  • @Spudley, well, I can check with the team if there are any exceptions to the rule but I'm not sure. As mentioned we are audited by multiple external parties in regards to security and policies. – reaper_unique Jun 28 '13 at 10:03
  • 2
    The fragment (# section) should never even be sent to the web server according to spec, so chances are your browser is doing something wrong there. – Joshua Walsh Jul 27 '13 at 13:36
  • 2
    Yes to what @YoshieMaster said. If the URL has a `#` *fragment*, that is never sent to the web server (or, therefore, to the firewall); it's only used internally by the browser. In this case, clicking a link tagged with ``...`` will not cause your browser to send any HTTP requests anywhere; all it will do is scroll to the top of the page. – Mark Reed Dec 10 '13 at 18:46
  • Another way to do this is to style it like a link with CSS, with `text-decoration: underline`, `cursor: pointer`, etc. Both have had support forever, though I don't know the first IE version that needed to be supported in 2011 when this answer was written. Of course, you could also use a button, or anything else, and style it the same way. – trysis Mar 20 '16 at 17:06
  • Is there a way to catch the triggered event for debugging those kind of links ? I've tried to activate the event listener breakpoints for mouse-> click, but then the debugger jumps to functions that are from different builted-in libraries. How can I know which functions would run when I click on the link, just to be able to put a breakpoint just at the one I want to debug ? – Roger Feb 14 '18 at 17:39
  • Thanks. Can the developer's alternative click-handler be invoked programmatically from javascript, using click(), or would that simply uselessly invoke the "javascript:;" – Zeek2 Jul 05 '18 at 11:32
53

basically instead of using the link to move pages (or anchors), using this method launches a javascript function(s)

<script>
function doSomething() {
  alert("hello")
}
</script>
<a href="javascript:doSomething();">click me</a>

clicking the link will fire the alert.

Eonasdan
  • 7,563
  • 8
  • 55
  • 82
38

There are several mechanisms to avoid a link to reach its destination. The one from the question is not much intuitive.

A cleaner option is to use href="#no" where #no is a non-defined anchor in the document.

You can use a more semantic name such as #disable, or #action to increase readability.

Benefits of the approach:

  • Avoids the "moving to the top" effect of the empty href="#"
  • Avoids the use of javascript

Drawbacks:

  • You must be sure the anchor name is not used in the document.
  • The URL changes to include the (non-existing) anchor as fragment and a new browser history entry is created. This means that clicking the "back" button after clicking the link won't behave as expected.

Since the <a> element is not acting as a link, the best option in these cases is not using an <a> element but a <div> and provide the desired link-like style.

CherryDT
  • 25,571
  • 5
  • 49
  • 74
Pau Giner
  • 1,282
  • 11
  • 11
  • 15
    I like the non-defined anchor too. However, another downside is that it adds the anchor to your browser history, so I opt to use the blank JS method in the OP. – John Reid Jan 10 '14 at 11:12
  • Is there any evidence that one method is faster than the other? – MaxRocket Feb 22 '22 at 18:46
13

It's used to write js codes inside of href instead of event listeners like onclick and avoiding # links in href to make a tags valid for HTML.

Interesting fact

I had a research on how to use javascript: inside of href attribute and got the result that I can write multiple lines in it!

<a href="
     javascript:
        a = 4;
        console.log(a++); 
        a += 2; 
        console.log(a++); 
        if(a < 6){ 
            console.log('a is lower than 6');
        } 
        else 
            console.log('a is greater than 6');
        function log(s){
            console.log(s);
        }
        log('function implementation working too');

">Click here</a>
  • Tested in chrome Version 68.0.3440.106 (Official Build) (64-bit)

  • Tested in Firefox Quantum 61.0.1 (64-bit)

CherryDT
  • 25,571
  • 5
  • 49
  • 74
Amir Fo
  • 5,163
  • 1
  • 43
  • 51
  • 4
    That is interesting - although absolutely horrible. Your answer finally explains what this actually really means :) – Enigma Plus Mar 02 '21 at 20:59
13
<a href="javascript:alert('Hello');"></a>

is just shorthand for:

<a href="" onclick="alert('Hello'); return false;"></a>
bjornd
  • 22,397
  • 4
  • 57
  • 73
  • 5
    Kind of but it's not a true "like for like" comparison. Which is a reason some fall into the trap of using it in the first place. – user692942 Jul 14 '15 at 15:45
12

It is a way of making a link do absolutely nothing when clicked (unless Javascript events are bound to it).

It is a way of running Javascript instead of following a link:

<a href="Javascript: doStuff();">link</a>

When there isn't actually javascript to run (like your example) it does nothing.

Daan Wilmer
  • 937
  • 4
  • 13
11

Refer to this:

<a href="Http://WWW.stackoverflow.com">Link to the website opened in different tab</a>
<a href="#MyDive">Link to the div in the page(look at the chaneged url)</a>
<a href="javascript:;">Nothing happens if there is no javaScript to render</a>
chutz
  • 2,256
  • 2
  • 25
  • 38
b k
  • 199
  • 1
  • 10
8
<a href="javascript:void(0);"></a>

javascript: tells the browser to execute the JavaScript code, and void(0) means, do nothing - don't reload, don't navigate, do not run any code.

MeSo2
  • 450
  • 1
  • 7
  • 18
Gowri
  • 16,587
  • 26
  • 100
  • 160
3

Old thread but thought I'd just add that the reason developers use this construct is not to create a dead link, but because javascript URLs for some reason do not pass references to the active html element correctly.

e.g. handler_function(this.id) works as onClick but not as a javascript URL.

Thus it's a choice between writing pedantically standards-compliant code that involves you in having to manually adjust the call for each hyperlink, or slightly non-standard code which can be written once and used everywhere.

1

Since it is a styling issue, instead of polluting the HTML with non valid syntax, you could/should use a W3 valid workaround:

  1. Format the HTML properly, without href, following the W3 accessibility guide lines for buttons.
  2. Use CSS to fix the initial goal of applying a clickable UX effect on a control.

Here's a live example for you to try the UX.

HTML

    <a role="button" aria-pressed="false">Underlined + Pointer</a>
    <a role="button" aria-pressed="false" class="btn">Pointer</a>

CSS

    a[role="button"]:not([href]):not(.btn) { text-decoration: underline; }
    a[role="button"]:not([href]) { cursor: pointer; }
chutz
  • 2,256
  • 2
  • 25
  • 38
  • The community encourages adding explanations alongisde code, rather than purely code-based answers (see [here](https://meta.stackoverflow.com/questions/300837/what-comment-should-i-add-to-code-only-answers)). – costaparas Feb 16 '21 at 05:28
1

I was searching for a solution that does not refresh pages but opens menu items on Ipads and phones. I tried it on also mobile, It works well

<a href="#" onclick="return false;">Dr</a>
Ergin Çelik
  • 719
  • 7
  • 14
-3
    1. Use that java script to Clear an HTML row Or Delete a row using the id set to a span and use JQuery to set a function to that span's click event.
    2. Dynamically set the div html to a string variable and replace {id} with a 1 or 2 etc. cell of a larger div table and rows

<div class="table-cell">
    <span id="clearRow{id}">
        <a href="javascript:" style-"color:#c32029; align:right; font-size:8pt;">Clear</a>
    </span>
</div>

<div class="table-cell">
   <span id="deleteRow{id}">
       <a href="javascript:" style-"color:#c32029; align:right; font-size:8pt;">Delete</a>
   </span>
</div>

//JQuery - Clear row
$("#clearRow" + idNum).click(function(){
    $("someIDOrWildcardSelector" + idNum).val("");
    $("someIDOrWildcardSelector" + idNum).val("");
    $("someIDOrWildcardSelector" + idNum).val("");
});

//JQuery to remove / delete an html row
$("#deleteRow" + idNum).click(function(){
    //depending upon levels of parent / child use 1 to many .parent().parent().parent()
    $(this).parent().remove();
});