Introducing CSS event:Selectors

—Tuesday, March 21 2006

Over the past 6 months or so Javascript has really gotten a lot of attention. I can’t name a web application released in the previous months (although I’m sure there are a few) that doesn’t use Javascript to provide an enhanced experience for users. I wanted a way to facilitate that interaction that doesn’t involve me repeating myself over and over wiring and rewiring event ovservers to a document.

In steps Behaviour. It was the right script at the right time and it got people thinking about how easy it was to separate a lot (not all) of your inline event handlers (onclick, onmouseover, onmouseout, etc) from your html documents. It worked great for it’s purpose and is still a viable solution today, however, I still found myself writing a lot of code to perform common task.

I use Prototype in most, if not all applications I’m involved with today. Prototype mixes well with Behaviour, however, there is a lot of duplicate functionality between the two scripts and I’m still writing way to much Javascript. Here is a common example for those of you using Behaviour with Prototype:

  var rules = {
    '#item li': function(element) {
      Event.observe(element, 'click', function(event) {
        var element = Event.element(element);
        element.setStyle({color: '#c00'});
      });
    },
    
    '#otheritem li': function(element) {
      Event.observe(element, 'click', function(event) {
        var element = Event.element(element);
        element.setStyle({color: '#c00'});
      });
    }
  }

This is the proper way to wire up events using Prototype and Behaviour. It’s a lot of code just to make a few things on the page change their font color. Now here is that same example using event:Selectors:

 var Rules = {
    '#item li:click, #otheritem li:click': function(element) {
      element.setStyle({color: '#c00'});
    }
  }

As you can see event:Selectors uses almost the exact same syntax you just don’t have to write near as much code. You use pseudo event selectors to apply events. You can also use the same callback for more than one selector encouraging code reuse.

I’ve setup a page for this with more examples and documentation. You can also grab the download from there.

Click here to view examples, docs, and to download event:Selectors