Snook.ca

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.

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.

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(..)

Sorry, comments are closed for this post. If you have any further questions or
comments, feel free to send them to me directly.

Hi. My name is Jonathan Snook and this is my site. I write about what interests me, which is usually web design, development, and technology. I'm also in the middle of a food adventure.
I wrote SMACSS. I tweet. Want to learn more?