views:

3043

answers:

6

Is it possible to animate a change in css using jquery?

If someone would be so kind as to provide me with an example i would be much obliged.

Essentially, i am trying to animate the sprites technique by manipulating the background-image in the css using jQuery. The goal is to animate the hover so that I get a nice fade instead of just the abrupt switch produced by the code below.

Here is where I'm at:

HTML:

<h1 id="solomon">Solomon</h1>

CSS:

body#default h1 {
text-indent: -9999px;
display: inline-block;
height: 213px;
}
body#default h1#solomon {
 background: transparent url(/images/S.gif) center top no-repeat;
 width: 183px;
 margin: 100px 0 0 216px;
 }

JQUERY:

$(function() {
$('h1').hover(function() {
    $(this).stop().css('background-position', 'center bottom');
}, function() {
    $(this).stop().css('background-position', 'center top');
});
});

Right now the it works fine, but there is no pretty animation on hover. I want to know how to animate the effect of switching the background-image placement.

Thanks to whomever takes a shot at this. :)

A: 

Take a look to jQuery.animate.

CMS
Check also this jQuery plug-in for animating backgroundPosition changes: http://www.corrupt-system.de/jquery/backgroundPosition/
CMS
+2  A: 

This article will get you started on the Two Image Technique

[UPDATE]

Found a better tutorial for you: This article will show you how to create a fading image (like a logo, for example)

Andreas Grech
A: 

@CMS: i tried revamping the jquery, as follows, according to the link you provided.. but no dice! :(

what gives?

JQUERY:

$(function() {
$('h1').hover(function() {
    $(this).stop().animate({
    background-position: 'center bottom'
    });
}, function() {
    $(this).stop().animate({
    background-position: 'center top'
    });
});
});
jon
A: 

i'm hoping someone can answer my question without pointing me to a tutorial? my issue with the tutorials is that they all force me to change my html which i am pretty locked into at this point.

also, why doesn't the animate function work in my above example (@CMS)?

thanks for your help everyone! :)

jon
+4  A: 

To create a fade effect you need to absolutely position one element on top of the other, and animate the element's opacity down to reveal the image beneath.

Since you can't change the HTML, I suggest you change the markup using JavaScript by dynamically inserting a span that will reveal the new image for your H1 tag.

I've put together a working example on jsbin.com that uses your markup (i.e. just the H1 tag). I've used the image from the jqueryfordesigners.com tutorial (since it's mine) so that you can get an idea of the CSS changes you need.

Specifically you need to style a nested SPAN in the H1 to be absolutely positioned within the H1 to allow it fade in:

http://jsbin.com/adike/ (to edit: http://jsbin.com/adike/edit/ )

Remy Sharp
A: 

You have to use this plugin to Animate Background Position :)

SalmanAbbas007