How to use a link to call JavaScript?

Javascript

Javascript Problem Overview


How to use a link to call JavaScript code?

Javascript Solutions


Solution 1 - Javascript

Unobtrusive JavaScript, no library dependency:

<html>
<head>
    <script type="text/javascript">

        // Wait for the page to load first
        window.onload = function() {

          //Get a reference to the link on the page
          // with an id of "mylink"
          var a = document.getElementById("mylink");

          //Set code to run when the link is clicked
          // by assigning a function to "onclick"
          a.onclick = function() {

            // Your code here...

            //If you don't want the link to actually 
            // redirect the browser to another page,
            // "google.com" in our example here, then
            // return false at the end of this block.
            // Note that this also prevents event bubbling,
            // which is probably what we want here, but won't 
            // always be the case.
            return false;
          }
        }
    </script>
</head>
<body>
    <a id="mylink" href="http://www.google.com">linky</a>        
</body>
</html>

Solution 2 - Javascript

<a onclick="jsfunction()" href="#">

or

<a onclick="jsfunction()" href="javascript:void(0);">

Edit:

The above response is really not a good solution, having learned a lot about JS since I initially posted. See EndangeredMassa's answer below for the better approach to solving this problem.

Solution 3 - Javascript

<a href="javascript:alert('Hello!');">Clicky</a>

EDIT, years later: NO! Don't ever do this! I was young and stupid!

Edit, again: A couple people have asked why you shouldn't do this. There's a couple reasons:

  1. Presentation: HTML should focus on presentation. Putting JS in an HREF means that your HTML is now, kinda, dealing with business logic.

  2. Security: Javascript in your HTML like that violates Content Security Policy (CSP). Content Security Policy (CSP) is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross-Site Scripting (XSS) and data injection attacks. These attacks are used for everything from data theft to site defacement or distribution of malware. Read more here.

  3. Accessibility: Anchor tags are for linking to other documents/pages/resources. If your link doesn't go anywhere, it should be a button. This makes it a lot easier for screen readers, braille terminals, etc, to determine what's going on, and give visually impaired users useful information.

Solution 4 - Javascript

And, why not unobtrusive with jQuery:

  $(function() {
    $("#unobtrusive").click(function(e) {
      e.preventDefault(); // if desired...
      // other methods to call...
    });
  });

HTML

<a id="unobtrusive" href="http://jquery.com">jquery</a>

Solution 5 - Javascript

Unobtrusive Javascript has many many advantages, here are the steps it takes and why it's good to use.

  1. the link loads as normal:

    <a id="DaLink" href="http://host/toAnewPage.html"&gt;click here</a>

this is important becuase it will work for browsers with javascript not enabled, or if there is an error in the javascript code that doesn't work.

  1. javascript runs on page load:

      window.onload = function(){
             document.getElementById("DaLink").onclick = function(){
                    if(funcitonToCall()){
                        // most important step in this whole process
                        return false;
                    }
             }
      }
    
  2. if the javascript runs successfully, maybe loading the content in the current page with javascript, the return false cancels the link firing. in other words putting return false has the effect of disabling the link if the javascript ran successfully. While allowing it to run if the javascript does not, making a nice backup so your content gets displayed either way, for search engines and if your code breaks, or is viewed on an non-javascript system.

best book on the subject is "Dom Scription" by Jeremy Keith

Solution 6 - Javascript

I think you can use the onclick event, something like this:

<a onclick="jsFunction();">

Solution 7 - Javascript

Or, if you're using PrototypeJS

<script type="text/javascript>
  Event.observe( $('thelink'), 'click', function(event) {
      //do stuff

      Event.stop(event);
  }
</script>

<a href="#" id="thelink">This is the link</a>

Solution 8 - Javascript

You can use a button and style it like a link: HTML code:

button {
width:0.0000000001px;
height:0.00000000001px;
  background-color: #ffffff;
  color: Blue;
  padding: 14px 20px;
  margin: 8px 0;
  border: none;
  cursor: pointer;
}

<button  onclick="function()"><u>Example button</u></button>

Solution 9 - Javascript

based on @mister_lucky answer use with jquery:

$('#unobtrusive').on('click',function (e) {
    e.preventDefault(); //optional
    //some code
});

Html Code:

<a id="unobtrusive" href="http://jquery.com">jquery</a>

Solution 10 - Javascript

just use javascript:---- exemplale

javascript:var JFL_81371678974472 = new JotformFeedback({ formId: '81371678974472', base: 'https://form.jotform.me/', windowTitle: 'Photobook Series', background: '#e44c2a', fontColor: '#FFFFFF', type: 'false', height: 700, width: 500, openOnLoad: true })

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJin YongView Question on Stackoverflow
Solution 1 - JavascriptEndangeredMassaView Answer on Stackoverflow
Solution 2 - JavascriptChelseaView Answer on Stackoverflow
Solution 3 - JavascriptMatt GrandeView Answer on Stackoverflow
Solution 4 - JavascriptMister LuckyView Answer on Stackoverflow
Solution 5 - JavascriptFire CrowView Answer on Stackoverflow
Solution 6 - JavascriptDavid ZView Answer on Stackoverflow
Solution 7 - JavascriptMark BiekView Answer on Stackoverflow
Solution 8 - JavascriptRohan KilambiView Answer on Stackoverflow
Solution 9 - JavascriptMostafa AsadiView Answer on Stackoverflow
Solution 10 - JavascriptDomi S HerdianView Answer on Stackoverflow