Href = "#" adds # to the page url
Let's say I have the following link:
<a href="#" onclick="alert('You clicked a link.');">Click Me!</a> Clicking this link will display a message and add a pound sign at the end of the page URL.
This doesnβt look very pretty - is there any way to avoid this other than using javascript in the url itself:
<a href="javascript:alert('You clicked a link.');">Click Me!</a> You must prevent the default response.
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 right now is to call the correct event property method:
<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 better to replace this # with a URI with the page you need, for people who donβt use JavaScript. In some jurisdictions, accessibility is actually 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;