206

How to use a link to call JavaScript code?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Jin Yong
  • 42,698
  • 72
  • 141
  • 187

11 Answers11

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

Community
  • 1
  • 1
Chelsea
  • 6,751
  • 5
  • 29
  • 31
226

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>
EndangeredMassa
  • 17,208
  • 8
  • 55
  • 79
  • 40
    Can you explain why this is better than the currently accepted answer, and where the script should go in the page (because this is pretty clearly a beginner-level question)? – Bill the Lizard Mar 28 '09 at 14:42
  • 8
    So what do I put in for the `href` if I don't want to redirect the user and just want to run some code? Edit: I see that it can be left blank: `href=""`. – SabreWolfy Jan 23 '12 at 14:12
  • 2
    This reloads the page though, so other form elements are reset. Using a "link" implementation to run the JavaScript does require reloading the page. – SabreWolfy Jan 23 '12 at 14:20
  • 4
    It won't redirect the browser. You should put the real url in the href even though your javascript will replace that action. That way, if they don't have javascript enabled, your link still works. – EndangeredMassa Jan 27 '12 at 08:06
  • 8
    Why is it better to add the `onclick` event via `window.onload`, rather than putting the `onclick` directly in the `` tag? – Nathan Reed Apr 14 '13 at 21:19
  • 1
    The primary reason is to separate the concerns of your markup and your behavior. Take a look at resources on the topic "Separation of Concerns in JavaScript". – EndangeredMassa Apr 15 '13 at 02:01
  • 1
    what if the a link needs to be called by class instead of id? – VUELA Aug 21 '13 at 19:03
  • 2
    You can use `document.getElementsByClassName` instead. – EndangeredMassa Aug 21 '13 at 19:43
  • 3
    What if element IDs are dynamic? This only works if you know what the ID will be. – cen Nov 05 '13 at 11:46
  • 13
    What if one of your concerns is that you don't want to separate your functional unit of work into different physical places in your source file, or spread over many source files. If you put a javascript call in your a href tag it is painfully clear by looking at one line what's going on. I would be concerned about separating that functionality into different physical places where it's harder to get a picture of what's going on. Maybe that's just my style. – stu Apr 11 '14 at 15:06
  • 4
    With a little more reflection, I don't disagree with the idea as a whole, but I think at some point (and this is one case) you can take it a little too far. – stu Apr 11 '14 at 15:08
  • @EndangeredMassa "You should put the real url in the href even though your javascript will replace that action." What real URL? Is there some URL form that will call javascript that I should be using here? It seems like you are assuming that this link will go to some page - if that's what I needed, I wouldn't be calling javascript from it. – Sean Worle Sep 07 '22 at 21:26
58
<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.

Matt Grande
  • 11,964
  • 6
  • 62
  • 89
  • 17
    Perhaps some description of the problems with this method? Is this worse than `href='#'` and `alert()` in `onclick`? – Thomas Ahle Aug 28 '15 at 22:14
  • 5
    I am new to javascript and don't understand what's wrong with this.. Any explanation would be nice – nilanjanaLodh Feb 14 '18 at 18:36
  • 1
    Hi, I am also unsure as to why not to use this? I am stuck in a scenario where I need to call a JS function, but all I can specify is a link. And your solution worked. – Ray Meyer Jun 13 '18 at 19:32
  • 1
    I also can't understand the edit reasons. 1) Every attribute (like all data-* attributes) are made for using advanced logic in html so this is normal and no problem at all 2) You can change any js on any site via the console. As long as you don't post sensible data into this field it is no more dangerous than any other function call. 3) If you don't need to support screen readers, braille terminals etc. it doesn't matter. – Insomnia88 Aug 18 '20 at 13:05
  • This worked perfectly for me. I needed to assign a method in a loop and was running into scope issues where clicking any link that had the method assigned to it called the last record in the loop. Not being a JS expert, this was a great, simple solution. – ScottSto Aug 03 '22 at 19:16
  • In my opinion that is the best and most stable way to do it for a single link. The only reason for other solutions with jQuery ect. would be if you have to change multiple links – Radon8472 Feb 24 '23 at 08:53
43

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>
Mister Lucky
  • 4,053
  • 2
  • 20
  • 18
  • 2
    Will this work for SEO such that crawlers will find the link and follow it? – Ahi Tuna Apr 12 '13 at 18:46
  • 16
    because not everybody uses jquery. – stu Apr 11 '14 at 14:21
  • 1
    @GregMiernicki Yes and no depending on what you mean by link. Look at the HTML. A webcrawler or any client with javascript turned off will visit the given HREF. Javascript enabled clients will run the click action and THEN follow the link if that function does not return a false value or call preventDefault. In this case, the href is a fallback, hence why it's called "unobtrusive" – Evan Langlois Sep 28 '16 at 05:56
  • @stu Update 2023: "because everybody shouldn't use jQuery". – Syed M. Sannan Apr 16 '23 at 20:08
  • 1
    @Stranger Thank the maker for computers. I get to enjoy this again 9 years later. – stu Apr 17 '23 at 21:52
13

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

Farvardin
  • 5,336
  • 5
  • 33
  • 54
Fire Crow
  • 7,499
  • 4
  • 36
  • 35
11

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

<a onclick="jsFunction();">
David Z
  • 128,184
  • 27
  • 255
  • 279
9

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>
Mark Biek
  • 146,731
  • 54
  • 156
  • 201
  • 1
    I love not having to put event handling functions in-line. – Mark Biek Mar 27 '09 at 01:51
  • 1
    It's the only way to go. Please vote down the inline answers. It's a practice for which there is no excuse these days. – Andrew Hedges Mar 27 '09 at 02:07
  • 5
    @Andrew: Please leave a comment along with your downvote explaining why the inline answers are bad. – Bill the Lizard Mar 28 '09 at 14:36
  • I wont say inline is bad. If you have a single link, that only should trigger ONE js function, calling this function inline is much clearer than spilling the call in multiple places in your code. Everyone who reads your code would need more documentation to understand where and why the click function is added to the link – Radon8472 Feb 24 '23 at 08:58
1

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

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>
Mostafa Asadi
  • 339
  • 4
  • 8
0

Why not just make it a button and style it like a link?

<button onclick = 'myFunction()' style='background-color: white; border: none; color: blue'>I look like a link</button>

function myFunction() {
alert("the cursor also reacts as if a normal link, while hovering the text; outside of this snippet")
}
<button onclick = 'myFunction()'; style='background-color: white; border: none; color: blue; cursor: pointer;'>I look like a link</button>
-6

Just use Javascript - example:

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 })
RoastBeast
  • 1,059
  • 2
  • 22
  • 38