From my experience I know three different ways to execute a JavaScript function when a user clicks on a link
Use the onclick
attribute on the link
<a href="#" onclick="myfunction();return false;">click me</a>
Use the href
on the link
<a href="javascript:myfunction();">click me</a>
Don't touch the link, do everything in js
<a href="#">click me</a>
(in the JavaScript we will stop the default event, and call the function)
Which one is better? What are the advantages and disadvantages?
EDIT deleted the "javascript:" on onclick
Use the onclick HTML attribute. The onclick event handler captures a click event from the users' mouse button on the element to which the onclick attribute is applied. This action usually results in a call to a script method such as a JavaScript function [...]
In JavaScript, you can call a function or snippet of JavaScript code through the HREF tag of a link. This can be useful because it means that the given JavaScript code is going to automatically run for someone clicking on the link. HREF refers to the “HREF” attribute within an A LINK tag (hyperlink in HTML).
This is a type of JavaScript link - the onclick attribute defines a JavaScript action when the 'onclick' event for the link is triggered (i.e. when a user clicks the link) - and there is a URL present itself in the onclick attribute.
To invoke this function in the html document, we have to create a simple button and using the onclick event attribute (which is an event handler) along with it, we can call the function by clicking on the button.
Unobtrusive Javascript (your third example) with graceful degredation is the best choice.
It is always good to have a link in the href attribute so as to support users who have disabled JavaScript on their browsers.
<a href="http://www.mywebsite.com/javascriptdisabled.html" onclick="myfunction(); return false;">click me</a>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With