How to use a link to call JavaScript code?
11 Answers
<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.
-
12I'd recommend the second one, as the first one scrolls you to the top of the page. – Matt Grande Mar 27 '09 at 01:39
-
7Yep it definitely will, unless you add a "return false;" after your function. – Chelsea Mar 27 '09 at 01:40
-
28This is 1998 code. Use one of the unobtrusive solutions. Please. – Andrew Hedges Mar 27 '09 at 02:05
-
10Use neither one! Links are for linking, they're not dummy elements to call javascript. – I.devries Mar 27 '09 at 07:19
-
4if your going to put javascript inline do it this way: – Fire Crow Mar 28 '09 at 15:34
-
3You should mention that jsfunction NEEDS the parenthesis to be called. i.e. `onclick="jsfunction()"`, otherwise, it won't do anything, as I learn from a question I made [here](http://stackoverflow.com/q/16944982/1385198) Despite the answer is not ideal (and very old now), I mention it to avoid confusion to others just like I was. – DiegoDD Jun 05 '13 at 16:52
-
Why not `` is there any benefit of using onclick and making the href as void-function? – Radon8472 Feb 24 '23 at 08:51
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>

- 17,208
- 8
- 55
- 79
-
40Can 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
-
8So 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
-
2This 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
-
4It 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
-
8Why 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
-
1The 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
-
2
-
3What if element IDs are dynamic? This only works if you know what the ID will be. – cen Nov 05 '13 at 11:46
-
13What 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
-
4With 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
-
For my understanding this is unnecessary complicated while `` is clear and easy to understand. Your suggestion makes only sense for me, when you need to add the same js-behavior to many different a-tags. – Radon8472 Feb 24 '23 at 08:49
<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:
Presentation: HTML should focus on presentation. Putting JS in an HREF means that your HTML is now, kinda, dealing with business logic.
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.
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.

- 11,964
- 6
- 62
- 89
-
17Perhaps 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
-
5I 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
-
1Hi, 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
-
1I 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
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>

- 4,053
- 2
- 20
- 18
-
2Will this work for SEO such that crawlers will find the link and follow it? – Ahi Tuna Apr 12 '13 at 18:46
-
16
-
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
-
-
1@Stranger Thank the maker for computers. I get to enjoy this again 9 years later. – stu Apr 17 '23 at 21:52
Unobtrusive Javascript has many many advantages, here are the steps it takes and why it's good to use.
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.
javascript runs on page load:
window.onload = function(){ document.getElementById("DaLink").onclick = function(){ if(funcitonToCall()){ // most important step in this whole process return false; } } }
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
I think you can use the onclick
event, something like this:
<a onclick="jsFunction();">

- 128,184
- 27
- 255
- 279
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>

- 146,731
- 54
- 156
- 201
-
1
-
1It'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
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>

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

- 339
- 4
- 8
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>

- 76
- 9
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 })

- 1,059
- 2
- 22
- 38