How to use a link to call JavaScript code?
10 Answers
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>
- 16,852
- 8
- 52
- 79
-
34Can 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
-
7So 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
-
6Why 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
-
1what if the a link needs to be called by class instead of id? – VUELA Aug 21 '13 at 19:03
-
2You can use `document.getElementsByClassName` instead. – EndangeredMassa Aug 21 '13 at 19:43
-
3What if element IDs are dynamic? This only works if you know what the ID will be. – cen Nov 05 '13 at 11:46
-
12What 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
<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
-
26This is 1998 code. Use one of the unobtrusive solutions. Please. – Andrew Hedges Mar 27 '09 at 02:05
-
8Use neither one! Links are for linking, they're not dummy elements to call javascript. – I.devries Mar 27 '09 at 07:19
-
4
-
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
<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,634
- 6
- 59
- 86
-
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
-
4I 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. – skapie19 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
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,033
- 2
- 19
- 18
-
2Will this work for SEO such that crawlers will find the link and follow it? – Ahi Tuna Apr 12 '13 at 18:46
-
13
-
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
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
- 5,168
- 5
- 31
- 53
- 7,179
- 4
- 35
- 35
I think you can use the onclick event, something like this:
<a onclick="jsFunction();">
- 122,461
- 26
- 246
- 274
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>
- 141,125
- 53
- 154
- 199
-
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
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>
- 269
- 4
- 8
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 })
- 35,543
- 12
- 29
- 39