Using JavaScript to trigger functions when a user clicks a link is a common requirement when developing apps. There are two ways to achieve this. Let’s assume the function we want to execute is called handleClick()
:
function handleClick() {
alert('clicked')
}
The first approach is to use a link with an href
value of “#” and an onclick
attribute:
<a href="#" onclick="handleClick()">Click here</a>
The second approach uses a link with an href
value of “javascript:void(0)” and an onclick
attribute:
<a href="javascript:void(0)" onclick="handleClick()">Click here</a>
The syntax is similar for both methods, with the only difference being the href
attribute value.
In the first method, if the user clicks the href="#"
link, you must ensure that you return false
from the event handler. Otherwise, the browser will scroll back to the top of the page:
function handleClick() {
alert('clicked')
return false
}
Even if you add the necessary code, if JavaScript is disabled or encounters an error, the browser will still scroll back to the top. To avoid this behavior, it’s recommended to use the second form, href="javascript:void(0)"
.
In both cases, if JavaScript is disabled or there are errors that prevent JavaScript execution, the handleClick()
function will not be called.
To address this issue, you can use a real URL in the href
attribute as a fallback. This way, if JavaScript is disabled or not functioning, the browser will navigate to the specified page using the GET HTTP method. However, using this fallback may not always be feasible or convenient.
Although best practices may not always be convenient, it’s important to consider them during the application design phase. Designing solely for the ideal use case without accounting for potential errors can lead to broken links and frustrated users.
Tags: JavaScript, href, function triggering, event handling