When I want some link to not do anything but only respond to JavaScript actions what is the best way to avoid the link scrolling to the top edge of the page?
I know several ways of doing it, they all seem to work fine:
<a href="javascript:void(0)">Hello</a>
or:
<a id="hello" href="#">Hello</a>
<script type="text/javascript>
$(document).ready(function() {
$("#toto").click(function(){
//...
return false;
});
});
</script>
and even:
<a id="hello" href="#">Hello</a>
<script type="text/javascript>
$(document).ready(function() {
$("#toto").click(function(event){
event.preventDefault();
//...
});
});
</script>
What is the difference between the above 3 examples?
PS: The above examples assume you are using jQuery but there are equivalents for mootools or prototype.
Binding:
javascript:
URLs are a horror to be avoided at all times;Responses:
return false
means both preventDefault
and stopPropagation
, so the meaning is different if you care about parent elements receiving the event notification;preventDefault
/stopPropagation
have to be spelled differently in IE usually (returnValue
/cancelBubble
).However:
<a>
isn't really the ideal markup for this. It'll go wrong if someone tries to middle-click it, or add it to bookmarks, or any of the other affordances a link has.#thatelementsid
and use unobtrusive scripting to grab the element ID from the link name. You can also sniff the location.hash
on document load to open that element, so the link becomes useful in other contexts.<input type="button">
or <button type="button">
. You can style it with CSS to look like a link instead of a button if want.<span>
instead. You can add a tabindex
property to make it keyboard-accessible in most browsers although this isn't really properly standardised. You can also detect keypresses like Space or Enter on it to activate. This is kind of unsatisfactory, but still quite popular (SO, for one, does it like this).<input type="image">
. This has the accessibility advantages of the button with full visual control, but only for pure image buttons.