When I want some link to not do anything but only respond to javascript actions what’s 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>
Do you have any preference ? why ? in which conditions ?
PS: of course the above examples assume you’re using jquery but there’s equivalents for mootools or prototype.
Binding:
javascript:URLs are a horror to be avoided at all times;Responses:
return falsemeans bothpreventDefaultandstopPropagation, so the meaning is different if you care about parent elements receiving the event notification;preventDefault/stopPropagationhave 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.#thatelementsidand use unobtrusive scripting to grab the element ID from the link name. You can also sniff thelocation.hashon 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 atabindexproperty 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.