Non-obtrusive JS rollovers with jQuery
Friday, May 22nd, 2009I thought I’d share a technique that I have grown very fond of over the last year - all made possible by jQuery’s syntactic bliss.
On many occassions in the past, I have found myself writing roll-over code that looks something like this:
<ul class="navigation"> <li onmouseover="this.className='selected';" onmouseout="this.className='';" class="selected"><a href="#">Link 1</a></li> <li onmouseover="this.className='selected';" onmouseout="this.className='';"><a href="#">Link 2</a></li> <li onmouseover="this.className='selected';" onmouseout="this.className='';"><a href="#">Link 3</a></li> </ul>
As you can see, the onmouseover/onmouseout makes the code less readable and takes up a lot of unnecessary space. One way to get rid of it is obviously to take advantage of the :hover pseudo class on the a element but if you want the hovered item to be the only item marked with the selected class then obviously that solution doesn’t cut it.
jQuery’s event wiring, along with its selector syntax allows you to remove the onmouse**** tags and earn some well deserved HTML karma.
JS
$lastActiveItem = null;
jQuery(document).ready(function(){
$('.navigation li').mouseover(function(){
$lastActiveItem = $('.navigation li.selected');
$('.navigation li').removeClass('selected');
$(this).addClass('selected');
});
$('.navigation li').mouseout(function(){
$('.navigation li').removeClass('selected')
$lastActiveItem.addClass('selected')
});
});