How to make this a tag working with href and onClick?
The default behavior of the <a>
tag’s onclick
and href
properties are to execute the onclick
, then follow the href
as long as the onclick
doesn’t return false
, canceling the event (or the event hasn’t been prevented).
Example of code make this a tag working with href and onClick (Add onclick event to hyperlink):-
<!DOCTYPE html>
<html>
<body>
<a href="https://tutorial.eyehunts.com//" onclick="return func();">Item</a>
<script type="text/javascript">
function func () {
alert("Hello")
}
</script>
</body>
</html>
Output:
Examples of JavaScript hyperlink onclick
Here are many ways to do put onClick function on hyperlink JS.
Bad:
<a id="myLink" href="javascript:MyFunction();">link text</a>
Good:
<a id="myLink" href="#" onclick="MyFunction();">link text</a>
Better:
<a id="myLink" href="#" onclick="MyFunction();return false;">link text</a>
Even better 1:
<a id="myLink" title="Click to do something" href="#" onclick="MyFunction();return false;">link text</a>
Even better 2:
<a id="myLink" title="Click to do something" href="PleaseEnableJavascript.html" onclick="MyFunction();return false;">link text</a>
Why better? because return false
will prevent browser from following the link
Best:
Use jQuery or other similar framework to attach onclick handler by element’s ID.
$('#myLink').click(function(){ MyFunction(); return false; });
Source: stackoverflow.com
Do comment if you have any doubts and suggestions on tutorial.
Note: The All HTML Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version