Udders
Udders

Reputation: 6986

animating a background image with jquery

I am having a view problems with animating a background to give the impression that a window is opening, I have the animation actually animating but it just animates like the images are in sequence. What I am wanting is to give the impression of a movie or animated gif.

You can see my current attempt here,

http://jsfiddle.net/8nj4934w/

I have so far done the following javascript,

    $('a').bind('mouseenter', function() {
    var self = $(this);
    this.iid = setInterval(function() {
       self.animate({ 'background-position-y': '-=500px' });           
    }, 300);
}).bind('mouseleave', function(){
    this.iid && clearInterval(this.iid);
});

and the kind of effect I am going for here,

http://www.jeld-wen.com/catalog/exterior-doors

just hover of a door image.

Upvotes: 2

Views: 58

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196236

Update (for jQuery solution handling two way sliding)

function slide(that, increment, limit){
    var self = $(that);
    that.iid && clearInterval( that.iid );

    that.pos = that.pos || 0;
    return setInterval(function () {
        that.pos = that.pos += increment;

        if (that.pos === limit){
            clearInterval(that.iid);
        } else {
            self.css({
                'background-position': '0 '+ that.pos + 'px'
            });
        }
    }, 50);
}

$('a').bind('mouseenter', function () {
    this.iid = slide( this, -500, -11500 );
}).bind('mouseleave', function () {
    this.iid = slide(this, 500, 0);
});

Demo at http://jsfiddle.net/g8cypadx/


Original answer I would suggest that you use CSS transitions with steps.

a {
  background-image: url('https://dl.dropboxusercontent.com/u/58586640/9100_FRONT_STRIP.png');
  background-repeat: no-repeat;
  height: 500px;
  width: 500px;
  display: block;
  background-position: 0 0;
  transition: background-position 1s steps(23);
}
a:hover {
  background-position: 0 -11500px; /* number of steps times the height */
}
<a href=""></a>


If you have to do it through jQuery then you should animate both properties but with 0 duration for the animation, and small delay for the interval

$('a').bind('mouseenter', function () {
    var self = $(this);
    this.iid = setInterval(function () {
        self.animate({
            'background-position': '-=0 -=500px'
        }, 0);
    }, 50);
}).bind('mouseleave', function () {
    this.iid && clearInterval(this.iid);
});

Demo at http://jsfiddle.net/8nj4934w/2/
(the problem with this solution is that it will not stop at the end)

Upvotes: 1

Related Questions