Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
JavaScript function in href vs. onClick
When creating clickable links that execute JavaScript, you can use either the href attribute with a JavaScript URL or the onclick event handler. Each approach has different behaviors and use cases.
Using href with JavaScript
The href attribute can execute JavaScript using the javascript: protocol. However, this approach has limitations with rapid clicks and can interfere with browser navigation.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript href Example</title>
<script>
function calculateSum() {
var sum = 0;
for (var i = 0; i < 1000; i++) {
sum += i;
}
alert("Sum using href: " + sum);
}
</script>
</head>
<body>
<a href="javascript:calculateSum()">Click me (href method)</a>
</body>
</html>
Using onclick Event Handler
The onclick event handler is more reliable and provides better control over the click behavior. It doesn't interfere with the browser's navigation system.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript onclick Example</title>
<script>
function calculateSum() {
var sum = 0;
for (var i = 0; i < 1000; i++) {
sum += i;
}
alert("Sum using onclick: " + sum);
}
</script>
</head>
<body>
<a href="#" onclick="calculateSum(); return false;">Click me (onclick method)</a>
</body>
</html>
Complete Comparison Example
<!DOCTYPE html>
<html>
<head>
<title>href vs onclick Comparison</title>
<script>
function showMessage(method) {
console.log(method + " method executed at: " + new Date().toLocaleTimeString());
alert("Executed using: " + method);
}
</script>
</head>
<body>
<h3>Test both methods:</h3>
<a href="javascript:showMessage('href')">href method</a><br><br>
<a href="#" onclick="showMessage('onclick'); return false;">onclick method</a>
</body>
</html>
Key Differences
| Aspect | href="javascript:" | onclick |
|---|---|---|
| Rapid clicks | May skip execution | Executes reliably |
| Browser history | May affect navigation | Clean with return false |
| Accessibility | Poor for screen readers | Better semantic meaning |
| Best practice | Avoid for JavaScript | Recommended approach |
Best Practices
When using onclick, always include return false; to prevent the default link behavior. For better semantic HTML, consider using <button> elements instead of links for JavaScript actions.
<!-- Recommended approaches --> <a href="#" onclick="myFunction(); return false;">Link with onclick</a> <button onclick="myFunction()">Button for JavaScript action</button>
Conclusion
Use onclick event handlers instead of href="javascript:" for better reliability and user experience. The onclick method handles rapid clicks properly and doesn't interfere with browser navigation.
