43

How to call javascript from a href?

like:

<a href="<script type='text/javascript'>script code</script>/">Call JavaScript</a>
KyleMit
  • 30,350
  • 66
  • 462
  • 664
user2033281
  • 527
  • 2
  • 7
  • 15

11 Answers11

43

<a onClick="yourFunction(); return false;" href="fallback.html">One Way</a>

** Edit **
From the flurry of comments, I'm sharing the resources given/found.

Previous SO Q and A's:

Interesting reads:

Community
  • 1
  • 1
Dawson
  • 7,567
  • 1
  • 26
  • 25
  • Is the `javascript:` prefix in the onclick needed...? – bwoebi May 02 '13 at 12:24
  • @Dawson - you don't need `javascript:` in the onclick property. – PhonicUK May 02 '13 at 12:25
  • 1
    Sure...if you're absolutely positive JavaScript is available. I don't like to rely on client-side. I don't like to rely on people knowing how to do anything in a UI (plan for the lowest common denominator -- even if it's intelligence of your visitors). – Dawson May 02 '13 at 12:25
  • 1
    @Dawson If there is no Js, the onclick attribute does exactly _nothing_. There's really no need for the `javascript:` prefix. – bwoebi May 02 '13 at 12:27
  • @PhonicUK -- maybe this is some old school carry over for me. When did that disappear? Or was it ever truly a requirement? Is it a cross-browser compatibility thing? I throw "javascript:" onto it without even thinking...My point is -- I didn't start that habit because I thought it was "a good idea" – Dawson May 02 '13 at 12:27
  • @Dawson, I don't think it was ever a requirement - just tolerated if seen. – PhonicUK May 02 '13 at 12:28
  • @Dawson and say that if you forget to return false, the link (fallback.html) will be called... – bwoebi May 02 '13 at 12:30
  • @PhonicUK - "tolerated if seen"? LOL. No friggin way. It was part of the spec at some point -- had to be. – Dawson May 02 '13 at 12:30
  • @Dawson, The HTML 4.01 Transitional spec (the oldest still widely used) doesn't specify it, neither does anything newer : http://www.w3.org/TR/html4/interact/scripts.html#adef-onclick – PhonicUK May 02 '13 at 12:32
  • @PhonicUK -- I'll get back to you on this. I've been putting it in JS solutions like the Q since 1997(?). I'm guessing it was needed for Netscape or IE back then. I was just learning the stuff, so I didn't question those things. Now it's a deeply ingrained habit. – Dawson May 02 '13 at 12:37
  • @Dawson: The `javascript:` in the `onclick` attribute and the `javascript:` in the `href` attribute are two completely different things. In `href`, i.e. the "URL", it's a pseudo-protocol to tell the browser to interpret the string as JavaScript. In `onclick` it is a label (https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/label) which are syntactically valid, but utterly useless in this case. See http://stackoverflow.com/questions/372159/do-you-ever-need-to-specify-javascript-in-an-onclick though. – Felix Kling May 02 '13 at 13:14
  • @FelixKling - Thanks. On my way into the shop today, I was thinking about how "javascript:" was probably the same type of psuedo as "mailto:". Still haven't had time to research the history. – Dawson May 02 '13 at 14:54
  • @FelixKling -- from that link you sent: "possible in IE to set the default language set to VBScript" << that's why we did it back then. Ironically, 99% of my career has been developing on a Mac. I have coded in a .NET environment, but I can't remember if we could call functions from the codebehind file or from the javascript. Don't have the means test such a theory now. Very interesting. – Dawson May 02 '13 at 15:36
24
<a href="javascript:call_func();">...</a>

where the function then has to return false so that the browser doesn't go to another page.

But I'd recommend to use jQuery (with $(...).click(function () {})))

bwoebi
  • 23,637
  • 5
  • 58
  • 79
  • 5
    One link. One page. Tack on a JS Library? We all had jobs before JQuery. We'll all have jobs when JQuery has been forgotten. – Dawson May 02 '13 at 12:42
  • @Dawson Before jQuery I hadn't coded anything ;-) ... But it doesn't seem to me as if JQ would be as fast forgotten... In ten years perhaps? Perhaps when there exist better alternatives... – bwoebi May 02 '13 at 12:43
  • I understand. But that's kind of the point. This question doesn't require a library. And it could have been asked and answered the same way 10 years ago. – Dawson May 02 '13 at 12:46
  • 1
    @Dawson Then you could also ask: what if the specification wouldn't support JS anymore, but something else? A library could there maybe replace the legacy JS code by parsing it and transforming it and then eval. — And the library code will work, once you have a working version on your server. – bwoebi May 02 '13 at 12:49
  • I'm not trying to be the devil's advocate here. The question is tagged [javascript] and [html]. JQuery is not synonymous with JavaScript. That's the biggest reason I was "arguing" against using a library. I realize in the world of web dev today, JQuery or the like is probably being used. – Dawson May 02 '13 at 14:51
  • @Dawson This was just a notice, that this is better in my opinion. I don't say that you have to use it. – bwoebi May 02 '13 at 15:20
  • I don't think you have to return false with `href="javascript:call_func();"` I think you just have to return false for `onclick="call_func()"`. I think returning false in href=javascript confuses some browsers. – Alex028502 Feb 10 '17 at 08:18
  • in firefox if I return false in javascript, I get `javascript:call_func();` in the url and "false" on the page. If I don't return anything, it works as expected. – Alex028502 Feb 11 '17 at 23:19
  • @bwoebi go to https://alex028502.github.io/return-from-href-javascript/ with firefox and click the 'test' button. I am using firefox 51.0.1 – Alex028502 Feb 12 '17 at 10:19
  • @Alex028502 ah, firefox. [Works perfectly in Safari.] Well… then don't return false :-) – bwoebi Feb 12 '17 at 13:28
12

The proper way to invoke javascript code when clicking a link would be to add an onclick handler:

<a href="#" onclick="myFunction()">LinkText</a>

Although an even "more proper" way would be to get it out of the html all together and add the handler with another javascript when the dom is loaded.

NilsH
  • 13,705
  • 4
  • 41
  • 59
3

Using JQuery would be good;

<a href="#" id="youLink">Call JavaScript </a>



$("#yourLink").click(function(e){
//do what ever you want...
});
Ahmet DAL
  • 4,445
  • 9
  • 47
  • 71
  • FYI - I'm guessing you're getting down votes because this question could have been posted in 1997. There was a solution then; however, JQuery wasn't around. – Dawson May 02 '13 at 12:31
  • I'm not. I'm saying, this solution doesn't require a JS library. Your comment suggests the web would fall apart if JQ wasn't around. – Dawson May 02 '13 at 12:39
  • You are assuming too much and i do not recommend there is no else solution for this. I just said it would be good. – Ahmet DAL May 02 '13 at 12:40
  • I'm not. The question is even tagged "javascript" "html". I made NO assumption. I used the requirements of the question/tags to formulate my answer. – Dawson May 02 '13 at 12:43
  • 1
    OK then. JQuery is one of Python libraries, not Javascript. – Ahmet DAL May 02 '13 at 12:46
  • +1 for showing this crispy, elegant solution. It's the best answer, when already on the jQuery track (and who is not these days?) – jboi Sep 07 '18 at 07:32
3

JavaScript code is usually called from the onclick event of a link. For example, you could instead do:

In Head Section of HTML Document

<script type='text/javascript'>
function myFunction(){
//...script code
}
</script>

In Body of HTML Document

<a href="#" id="mylink" onclick="myFunction(); return false">Call JavaScript </a>

Alternatively, you can also attach your function to the link using the links' ID, and HTML DOM or a framework like JQuery.

For example:

In Head Section of HTML Document

<script type='text/javascript'>
document.getElementById("mylink").onclick = function myFunction(){ ...script code};
</script>

In Body of HTML Document

<a href="#" id="mylink">Call JavaScript </a>
KernelPanik
  • 8,169
  • 1
  • 16
  • 14
3

I would avoid inline javascript altogether, and as I mentioned in my comment, I'd also probably use <input type="button" /> for this. That being said...

<a href="http://stackoverflow.com/questions/16337937/how-to-call-javascript-from-a-href" id="mylink">Link.</a>

var clickHandler = function() {
     alert('Stuff happens now.');   
}


if (document.addEventListener) {
    document.getElementById('mylink').addEventListener('click', clickHandler, false);
} else {
    document.getElementById('mylink').attachEvent('click', clickHandler);
}

http://jsfiddle.net/pDp4T/1/

2

Not sure why this worked for me while nothing else did but just in case anyone else is still looking...

In between head tags:

<script>
     function myFunction() {
           script code
     }
</script>

Then for the < a > tag:

<a href='' onclick='myFunction()' > Call Function </a>
2
 <a href="javascript:
  console.dir(Object.getOwnPropertyDescriptors(HTMLDivElement))">
       1. Direct Action Without Following href Link
  </a>

<br><br>

  <a href="javascript:my_func('http://diasmath.blogg.org')">
      2. Indirect Action (Function Call) Without Following Normal href Link
  </a>

<br><br>

 <!-- Avec « return false » l'action par défaut de l'élément
 // <a></a> (ouverture de l'URL pointée par
 // « href="http://www.centerblog.net/gha" »)
 // ne s'exécute pas.
 -->
 <a target=_new href="http://www.centerblog.net/gha"
          onclick="my_func('http://diasmath.blogg.org');
 return false">
     3. Suivi par défaut du Lien Normal href Désactivé avec
     « return false »
  </a>

<br><br>

 <!-- Avec ou sans « return true » l'action par défaut de l'élément
 // s'exécute pas.
 -->
 <a target=_new href="http://gha.centerblog.net"
          onclick="my_func('http://diasmath.blogg.org');">
     4. Suivi par défaut du Lien Normal href Conservé avec ou sans
     « return true » qui est la valeur retournée par défaut.
  </a>

<br><br>

<!-- Le diese tout seul ne suit pas le lien href. -->
  <a href="#" onclick="my_func('http://diasmath.blogg.org')">
      5. Lien Dièse en Singleton (pas de suivi href)
  </a>

  <script language="JavaScript">
   function my_func(s) {
       console.dir(Object.getOwnPropertyDescriptors(Document));
       window.open(s)
   }
  </script>

<br>
<br>

 <!-- Avec GESTION D'ÉVÉNEMENT.
 // Événement (event) = click du lien
 // Event Listener = "click"
 // my_func2 = gestionnaire d'événement
 -->
  <script language="JavaScript">
   function my_func2(event) {
      console.dir(event);
      window.open(event.originalTarget["href"])
   }
  </script>
 <a target=_blank href="http://dmedit.centerblog.net"
     id="newel" onclick="return false">
     6. By specifying another eventlistener
     (and deactivating the default).
  </a>
  <script language="JavaScript">
      let a=document.getElementById("newel");
      a.addEventListener("click",my_func2)
  </script>
1

If you only want to process a function and not process the href it self, add the return false statement at the end of your function:

 <a href="#" onclick="javascript: function() {... ; return false} return false">click</>
Yannick G
  • 96
  • 5
  • Three remarks: 1) `javascript:` is useless here and 2) you defined a function but never call it. 3) The way you define the function probably results in a syntax error. – Felix Kling May 02 '13 at 13:16
0

another way is :

<a href="javascript:void(0);" onclick="alert('testing')">
vanessen
  • 1,125
  • 1
  • 12
  • 19
0

Edit This will create a link with Edit after clicking on editing a function name as edit will be called.