Using MooTools for Button Effects
The last few articles here have dealt with using CSS to create custom buttons with hover and click effects. While in a perfect world, the CSS versions would be enough, but in a world with MSIE, they fall a little short. Some versions of MSIE only allow active and hover effects on <a> tags, but what if you want to create a custom button using some other type of tag? For that case, you’ll have to resort to using Javascript.
There are many different Javascript libraries to make cross-browser differences fade away, but I have been leaning towards using MooTools. So my example here will be shown using MooTools, but I would imagine most of the other Javascript libraries would work as well.
The first thing we need to do is change our CSS code to use class names rather than the :active and :hover pseudo-classes. The new CSS code is shown below with the old selectors commented out for reference.
/* Old Selectors: #nav a:hover, #nav a:hover span */
#nav .btn-hover, #nav .btn-hover span {
color: #2A5E5E;
background-position: left -22px;
}
/* Old Selector: #nav a:hover */
#nav .btn-hover {
background-position: right -22px;
}
/* Old Selectors: #nav a:active, #nav a:active span */
#nav .btn-click, #nav .btn-click span {
color: #74A074;
background-position: left -44px;
}
/* Old Selector: #nav a:active */
#nav .btn-click {
background-position: right -44px;
}
Just so you don’t have to go back and look, our original HTML code was as follows.
<div id="nav"> <a href="#"><span>OK</span></a> <a href="#"><span>Cancel</span></a> </div>
In order for these new selectors to work, we have to apply the btn-hover and btn-click classes at the appropriate times. The events we are going to use are mouseover/mouseout for the hover effects, and mousedown/mouseup for the click effects. MooTools makes it insanely easy to add events to multiple elements using the $$ function in combination with the addEvents method. The code to do this is shown below.
window.addEvent('domready', function() {
$$('#nav > *').addEvents({
'mouseover': function(e) { this.addClass('btn-hover') },
'mouseout': function(e) { this.removeClass('btn-hover') },
'mousedown': function(e) { this.addClass('btn-click') },
'mouseup': function(e) { this.removeClass('btn-click') }
})
})
You’ll, of course, have to include the MooTools Core and More scripts from the MooTools web site. As you can see from the code above, the btn-hover class is added and removed by the mouseover and mouseout events, respectively. And the btn-click class is added and removed by the mousedown and mouseup events, respectively. The $$ function is selecting all immediate children of the element with ID of “nav”. In this case, that would be the <a> elements. With all of this in place, all of the button effects should work in all browsers now even if you use elements other than <a>.
