Skip to content

Anchor tag onclick call JavaScript function | Example Code

  • by

First, you have to block href call URL if don’t want to open the tab/window or other operations. You can call a function in 2 ways using the href or onclick attribute in the HTML tag.

Function inside href

<a href="javascript:someFunction()">LINK</a>

JavaScript link href=#” onclick

<a href="#" onclick="someFunction(); return false;">LINK</a>

Anchor tag onclick call JavaScript function Examples

HTML example code:

<!DOCTYPE HTML>

<html>
<body>

	<a href="javascript:add(1,2)" id="fo">JS Add Numbers</a>

	<script>
		function add(a,b){
			alert(a+b);
		}
   </script>

</body>
</html>

Or

<!DOCTYPE HTML>

<html>
<body>

	<a href="#" onclick="Hello(); return false;">LINK</a>

	<script>
		function Hello(){
			console.log("Hello function")
		}
   </script>

</body>
</html>

Output:

Anchor tag onclick call JavaScript function

Do comment if you have any doubts or suggestions on this JS <a> topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading