Fez Vrasta
Fez Vrasta

Reputation: 14815

Equivalent of @keyframes for jQuery

I'm looking for a way to emulate the CSS @keyframes animations using jQuery.

I need to change the background image each x seconds following a list of images provided when the user moves mouse over an element.
The CSS animations should be:

.readon:hover {
    animation: readonin 2s;
}

@keyframes readonin {
     0% { background-image: url(1.png); }
    50% { background-image: url(2.png); }
   100% { background-image: url(3.png); }
}

I've found plugins like Spritely but they works with sprites and I need instead to change the image background of the element.
Use the set-interval function of Javascript seems a bad solution because I can't find a way to stop the animation when the user moves the mouse out of the element.

Upvotes: 0

Views: 1427

Answers (2)

alex
alex

Reputation: 490163

Use something like...

var images = ["1.png", "2.png", "3.png"];
var $element = $(".readon");
var interval = null;
$element.hover(function () {
    var $this = $(this);
    var i = 0;
    var fn = function () {
        $this.css("background-image", "url(" + images[i] + ")");
        i = ++i % images.length;
    };
    interval = setInterval(fn, 666);
    fn();
},
function () {
    clearInterval(interval);
    $(this).css("background-image", "none");
});

jsFiddle of a similar concept (with background colours).

It should be clear enough to see what's going on. Basically we start looping over the images and setting them as the background image on mouse over, and reset it when the mouse leaves.

Upvotes: 3

DGS
DGS

Reputation: 6025

You can use a library like jQuery-Keyframes to generate new keyframes at runtime if that is what you are after.

Upvotes: 1

Related Questions