[javascript] How to call javascript from a href?

How to call javascript from a href?

like:

<a href="<script type='text/javascript'>script code</script>/">Call JavaScript</a>

This question is related to javascript html

The answer is


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>

Using JQuery would be good;

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



$("#yourLink").click(function(e){
//do what ever you want...
});

<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 () {})))


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/


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</>

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.


another way is :

<a href="javascript:void(0);" onclick="alert('testing')">

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>

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


 <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>