jon
jon

Reputation: 123

How to animate a change in css using jQuery

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


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! :)

Upvotes: 1

Views: 9601

Answers (3)

Celmaun
Celmaun

Reputation: 24752

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

Upvotes: 1

Remy Sharp
Remy Sharp

Reputation: 4560

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/ )

Upvotes: 3

Andreas Grech
Andreas Grech

Reputation: 107950

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)

Upvotes: 2

Related Questions