Jan. 22, 2009 at 11:21amGiving Actions to Classes

Actions without JavaScript!

A concept of how to define actions using classes. Best part is, there's no need to know JavaScript!

While working on a site with a lot of transition effects on it I came up with a quick way to setup actions without writing extra JavaScript. I present this idea with the hopes of refining the technique.

The basic idea is to define elements with classes that tell JavaScript was events to give them. As an example, look at the following HTML:

<button class="action show-content">Show Content</button>
<p class="content hidden">This is some content.</p>

It would look as though the button should be given the action of showing the paragraph element. In jQuery, you would normally just do:

$(function() {
    $('.show-content').click(function() {
        $('.content').slideDown();
    });
});

I found myself using this pattern over an over. Each code block does roughly the same thing. And in computer science, if you find a pattern, try to abstract it and make it more general. That lead to the following code:

$(function() {
    $('.action').click(function() {
        $.map(this.className.split(' '), function(className) {
            var classNames = className.split('-');
            var action = classNames.shift();
            var elems = $('.'+classNames.join('-'));
            switch(action) {
                case 'show': elems.slideDown(); break;
                case 'hide': elems.slideUp(); break;
                case 'toggle': elems.slideToggle(); break;
                case 'checkall': elems.attr('checked', true); break;
                case 'uncheckall': elems.attr('checked', false); break;
            }
        });
    });
});

Here's what this does. First, it finds all the elements with the class of "action". It then looks at all of it's classes. It will then find what action to run based off the keyword. It will then look at the rest of the class name and select all the elements that match. In my example above, the keyword is "show" and the elements are "content. We could change the "show" keyword to "toggle" and that will completely change it's action.

An interesting side effect is that you can change these classes dynamically, and because the click action is still set, the action will change without a new event listener.

How do we use it?

Create an element with content in it and give it any class name (other then "action" or one of the keywords). Then create an element and give it a class name of "action keyword-classname". It's really just that simple!

Add your comment below

Leave a Comment

Remember me

Name:

Email:

URL:

Comment: * No HTML, http:// will auto-link
* required
Comment Guidelines