Let's say I have the following link:
<a href="#" onclick="alert('You clicked a link.');">Click Me!</a>
When clicked this link will alert a message as well as appending a pound sign on the end of the page url.
This doesn't look very pretty is there any way to avoid it besides using javascript in the url itself:
<a href="javascript:alert('You clicked a link.');">Click Me!</a>
You have to prevent the default response from occurring.
The old-fashioned approach is to return false
from it:
<a href="#" onclick="alert('You clicked a link.'); return false;">Click Me!</a>
Or, better:
<a href="#" id="myLink">Click Me!</a>
<script type="text/javascript">
window.onload = function() {
document.getElementById('myLink').onclick = function(event) {
alert('You clicked a link.');
return false;
};
};
</script>
The best approach nowadays is to call the proper method of the event
property:
<a href="#" id="myLink">Click Me!</a>
<script type="text/javascript">
window.onload = function() {
document.getElementById('myLink').onclick = function(event) {
alert('You clicked a link.');
event.preventDefault(); // <---
};
};
</script>
It's also best to replace that #
with an URI to some proper page, for people not using JavaScript. In some jurisdictions, accessibility is in fact a legal requirement.
Edit Fixed for bleedin' IE:
function f() {
document.getElementById('myLink').onclick = function(e) {
alert('You clicked a link.');
if (!e) {
var e = window.event;
}
// e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = false;
// e.stopPropagation works only in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
};
window.onload = f;
The trick is return false
on the event handler.
<a href="" onclick="alert('You clicked a link.'); 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