- How to call a javascript function from href tag in html?
- Method 1: Using the «onclick» attribute
- Method 2: Using the «addEventListener» method
- Method 3: Using the «javascript:» pseudo-protocol
- How to Pass Reference to “this” on href JavaScript Function
- Example
- Code Example
- Conclusion
- Get Set Remove HREF In Javascript (Simple Examples)
- TLDR – QUICK SLIDES
- TABLE OF CONTENTS
- JAVASCRIPT HREF
- 1) GET, CHANGE, REMOVE HREF
- 1A) GET HREF
- 1B) SET HREF TO URL
- 1C) SET HREF TO JAVASCRIPT FUNCTION
- 1D) REMOVE HREF
- 2) ONCLICK & JAVASCRIPT HREF
- 3) ONCLICK & URL LINK TOGETHER
- DOWNLOAD & NOTES
- SUPPORT
- EXAMPLE CODE DOWNLOAD
- EXTRA BITS & LINKS
- EXTRA) JAVASCRIPT VOID!?
- INFOGRAPHIC CHEAT SHEET
- LINKS & REFERENCES
- THE END
- Leave a Comment Cancel Reply
- Search
- Breakthrough Javascript
- Socials
- About Me
How to call a javascript function from href tag in html?
Sometimes it’s necessary to call a JavaScript function from an HTML element, such as a button or a hyperlink (« tag). However, when using the `href` attribute on an anchor tag, it’s common to encounter issues where the function is not executed as expected or causes the page to refresh. In this scenario, you need to prevent the default behavior of the `href` attribute and use a different approach to call your JavaScript function. Here are a few methods to accomplish this:
Method 1: Using the «onclick» attribute
To call a JavaScript function from an href tag in HTML using the «onclick» attribute, follow these steps:
function showAlert() alert("Hello, world!"); >
- Next, create an anchor tag with the «onclick» attribute set to the name of the function you want to call. Here’s an example:
a href="#" onclick="showAlert()">Click mea>
In this example, the «#» in the href attribute prevents the page from reloading when the link is clicked.
- You can also pass parameters to the function by adding them to the onclick attribute. Here’s an example:
a href="#" onclick="showAlert('Hello')">Click mea>
In this example, the function showAlert() takes a parameter, which is the string «Hello».
a href="#" onclick="function()showAlert();>()">Click mea>
In this example, an anonymous function is created that calls the showAlert() function.
That’s it! By following these steps, you can call a JavaScript function from an href tag in HTML using the «onclick» attribute.
Method 2: Using the «addEventListener» method
To call a JavaScript function from an href tag in HTML using the «addEventListener» method, you can follow these steps:
- First, create an anchor tag in your HTML with an id attribute that matches the function name you want to call:
a href="#" id="myFunction">Click mea>
- Finally, use the «addEventListener» method to attach a click event listener to the anchor tag and call the JavaScript function when the anchor tag is clicked:
document.getElementById("myFunction").addEventListener("click", myFunction);
Here’s the complete code example:
DOCTYPE html> html> head> title>Call JavaScript function from href tag using addEventListenertitle> head> body> a href="#" id="myFunction">Click mea> script> function myFunction() console.log("Hello world!"); > document.getElementById("myFunction").addEventListener("click", myFunction); script> body> html>
Method 3: Using the «javascript:» pseudo-protocol
To call a JavaScript function from an href tag in HTML using the «javascript:» pseudo-protocol, you can follow these steps:
function myFunction() alert("Hello World!"); >
- In your HTML code, create an anchor tag with the href attribute set to «javascript:» followed by the name of the function. For example:
a href="javascript:myFunction()">Click here to call myFunction()a>
- Alternatively, you can pass parameters to the function by including them in the «javascript:» URL. For example:
a href="javascript:myFunction('John', 'Doe')">Click here to call myFunction() with parametersa>
function myFunction(firstName, lastName) alert("Hello " + firstName + " " + lastName + "!"); >
- You can also use the «void» operator to prevent the browser from navigating to a new page when the link is clicked. For example:
a href="javascript:void(myFunction())">Click here to call myFunction() without navigatinga>
function myFunction() alert("Hello World!"); >
That’s it! By using the «javascript:» pseudo-protocol, you can easily call JavaScript functions from href tags in HTML.
How to Pass Reference to “this” on href JavaScript Function
When using JavaScript, it’s common to need to pass a reference to the current object or element. One case where this is useful is when working with event handlers, such as the `onclick` of an anchor tag («). In this guide, we’ll show you how to pass a reference to `this` on an `href` JavaScript function.
Example
Let’s start with a simple example. Suppose we have an anchor tag like this:
And we want to pass a reference to the anchor tag (`this`) to the `myFunction()` function:
To pass a reference to `this`, we can use the `call()` method. Here’s how to do it:
Now, when `myFunction()` is called, `this` will refer to the anchor tag that was clicked.
Code Example
Here’s a more complete example that demonstrates passing a reference to `this` on an `href` JavaScript function:
Click me function myFunction()
When you click the “Click me” link, the `myFunction()` function will be called, and `this` will refer to the anchor tag that was clicked. The `console.log()` statement will output the anchor tag to the console.
Conclusion
Passing a reference to `this` on an `href` JavaScript function is easy using the `call()` method. By doing so, you can easily access the current object or element in your event handlers.
Get Set Remove HREF In Javascript (Simple Examples)
Welcome to a quick tutorial on how to get, set, and remove the href property in Javascript. By now, you should know href very well. That “thing” we use to specify which webpage to link to. But how can we dynamically change or remove it using Javascript? For a quick answer:
- To get the href – var link = document.getElementById(«ID»).href;
- To set the href – document.getElementById(«ID»).href = «http://site.com»;
- Alternatively, to set the href to run a Javascript function – document.getElementById(«ID»).href = «javascript:FUNCTION()»;
- To remove the href – document.getElementById(«ID»).removeAttribute(«href»);
That covers the quick basics, but read on for more examples!
TLDR – QUICK SLIDES
TABLE OF CONTENTS
JAVASCRIPT HREF
All right, let us just now get into the mechanics of href, and a few ways we can work with it in Javascript.
1) GET, CHANGE, REMOVE HREF
1A) GET HREF
Yes, it’s as simple as that. We can get the current href with ELEMENT.href .
1B) SET HREF TO URL
To set or change the href of a link, simply assign a new one – ELEMENT.href = «http://site.com» .
1C) SET HREF TO JAVASCRIPT FUNCTION
function foo () < alert("Foo!"); >function hrefsetjs ()
We can also set the href to run a Javascript function. But I am personally not a fan of this… Will explain more below.
1D) REMOVE HREF
- Setting an empty href – ELEMENT.href = «»
- Or removing it entirely – ELEMENT.removeAttribute(«href»)
- An empty href is equivalent to pointing to the current page itself href=»#» .
- But entirely removing the href will result in a “do nothing when clicked” link.
2) ONCLICK & JAVASCRIPT HREF
As you already know, we can use href=»javascript:FUNCTION()» to run a Javascript function. But take note that we can also attach onclick=»FUNCTION()» to do the same. What happens if we do both onclick and href=»javascript:» together? As the above example turns out, dummyB() will run first, followed by dummyA() .
But personally, I am not a fan of using href=»javascript:» . It is actually a mechanism from the past, and it is plain confusing. Just stick with onclick . If you need to run multiple functions on click, then just do onclick=»FUNCTION(); FUNCTION();» . There’s really no need to do any of the funky javascript:FUNCTION() stuff.
3) ONCLICK & URL LINK TOGETHER
Lastly, let us try out another “funky combination” – We have a href=»URL» link and an onclick attached. So what happens here is, the onclick will run first before opening the URL link. At least on Google Chrome.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SUPPORT
600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for this guide, and here is a small section on some extras and links that may be useful to you.
EXTRA) JAVASCRIPT VOID!?
In some tutorials, you may spot something like this:
Basically, this means “do nothing on click”. But be warned – This is a blast from the past, and don’t do this anymore. In modern-day HTML and Javascript, we simply remove the href attribute.
INFOGRAPHIC CHEAT SHEET
LINKS & REFERENCES
THE END
Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
Leave a Comment Cancel Reply
Search
Breakthrough Javascript
Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!
Socials
About Me
W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.
Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.