Javascript: Preventing Default Event Actions

Sometimes, browsers respond to user interactions in bothersome ways. Imagine a scenario where you have a list of links, all bound to Javascript events which toggle the CSS display value of different div elements. Or maybe you're making Ajax calls for a tabbed content area or the like. Perhaps the code for the links or tabs or whatever looks like this...

<ul>
    <li><a href="#one">One</a></li>
    <li><a href="#two">Two</a></li>
    <li><a href="#three">Three</a></li>
</ul>

In observing the anchored values, a browser's default reaction is to reposition the viewing pane to the appropriately named A element. If that named element doesn't exist, the viewing pane is thrown back to the top of the content, potentially screwing up the user's focus. This is typically a problem on pages where the user has scrolled down to view the content below the fold, clicked a link with a hashed value, eg. "#" and watched the scrollbar hop back to the top of the window.

So what follows are several ways to prevent this behavior from taking place. By stopping these default actions, we avoid the risk of frustrating the user and make their experience more enjoyable.

Javascript

<a href="#one" onclick="return false;">One</a>

Mootools 1.11

<script>
$('a').addEvent('click',function(event) {  
    var e = new Event(event); 
        e.stop();  
});
</script>

Mootools 1.2

<script>
$('a').addEvent('click',function(event) {  
    event.preventDefault();  
});
</script>

jQuery

<script>
$('a').bind('click',function() { 
    return false; 
});
</script>

Prototype

<a id="myLink" href="#one" onclick="return false;">One</a>
<script>
Event.observe('myLink', 'click', function(event) {  
    Event.stop(event);  
}); 
</script>

MochiKit

<script>
connect('myLink', 'onclick', function(e) { e.stop(); });
</script>

Yahoo! UI Library

<script>
var a = document.getElementById('myLink'); 
    a.onclick = function (e) {
        e = e || event;
        YAHOO.util.Event.preventDefault(e);
    };
</script>

Reply

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.