Preventing default event behavior with Javascript

Posted: 03/29/2009

with examples using jQuery and Prototype

Let’s say we want to disable all the links on a page, using jQuery we just have to return false from the click handler:

  jQuery(function(){
    jQuery('body a').click(function(){
      return false;
    });
  });

Using Prototype, we pass the event instance to Event.stop():

  document.observe("dom:loaded", function(){
    $$('body a').each(function(a, num){
      $(a).observe('click', function(e){
        Event.stop(e);
      });
    });
  });

With everyday Javascript, we again return false from the click handler:

  window.onload = function(){
    elements = document.getElementsByTagName('a');
    for (var i = 0; i < elements.length; i++){
      elements[i].onclick = function(){
        return false;
      }
    }
  }

About Me

I'm a skier, web developer, entrepreneur, freelancer, and all around stand-up guy living in Manhattan. This is me, repping one of my favorite shirts...

Follow me on twitter or send me an email.

All Posts

Music Blogs