Handling Active State for jQuery Animated Backgrounds
Awhile back, I wrote an article on how to animate background images with jQuery to create some nifty effects. One of the most common questions I receive on that article is, "How do I handle active states?" It is time to answer that question.
There are two ways in which you can handle the active state:
- Create a different animation for active elements; or
- Change the background image to be animated.
The HTML
The HTML for this is exactly the same as before except an active class would be applied to the LI
. You can add the active class to the link, if you wish. You just need to update the code below accordingly.
<ul>
<li><a href="…"></a></li>
<li class="active"><a href="…"></a></li>
<li><a href="…"></a></li>
</ul>
Different Animation for Active Elements
This should hopefully be very straightforward: just create two sets of animation. One will animate on any element that is not with an active class and another will animate on any element that does have an active class.
$('#nav li:not(.active) a')…
$('#nav li.active a')…
The rest of the code will be tailored to handle the animation however you wish.
Change the Background Image
This is by far the more optimized of the two solutions as the amount of additional JavaScript required is absolutely zero but is based on the assumption that the animation will be exactly the same.
All that needs to be done is to have the background image set to something else for the active state.
#a a { background:url(bg.jpg) repeat -20px 35px; }
#a .active a { background-image:url(bg-active.jpg); }
And that's it!
Conversation
Nice and simple solution!
One thing that crossed my mind is that I usually remove the link in the active li, sometimes replaces it with a span-element for styling purposes. If CSS isn't supported (e.g mobile-devices) I can more easily understand where I am in the navigation-element.
This was a very confusing title. I thought you'd talk about the :active selector to make this keyboard accessible. As it is I agree that the current section should never be a link - it is linking to the page you are on. I normally replace it with a strong to make it obvious even for non-css browsers
Nice one Jonathan. I usually remove hover states or animations from active elements so i don't use 2 different animations for active and non-active elements. I just apply all animations to $('#nav li:not(.active) a').hover(..)
I always loved jQuary, This makes me love it all the more.
Thank Snook
But I use another way to show active elements.
I use css !Important and it's work.
Is it possible that it doesn't work in IE?