2

How do I offset the background-position, let's say 20px, from its original position?

Like:

$(".selector").animate("slow").css("backgroundPosition", "center -=20px");

(That obviously doesn't work... But how do I do this??)

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
curly_brackets
  • 5,491
  • 15
  • 58
  • 102

3 Answers3

1

jQuery by default does not animate backgrounds. There is this short code that can enable that. After you add it your code should work but first fix it like this:

$(".selector").animate({ "backgroundPosition": "center -=20px" },"slow");

Taken from:

http://snook.ca/archives/javascript/jquery-bg-image-animations

Demo:

http://snook.ca/technical/jquery-bg/

amosrivera
  • 26,114
  • 9
  • 67
  • 76
1

Animating CSS background-position works with standard jQuery .animate(), as in this example.

HTML

<p>Lorem ipsum</p>

CSS

p {
    height:50px;
    width:200px;
    background-image:url(http://lorempixum.com/200/50);
}

JavaScript

$('p').animate({'backgroundPosition':'-20px'}, 'slow');
andyb
  • 43,435
  • 12
  • 121
  • 150
0

You want to animate it or just change it?

You can change it by doing something like:

var newPos = parseFloat(($('.selector').css('backgroundPosition').replace('px', ''))+20) + "px";
$('.selector').css('backgroundPosition', newPos);
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Rebecca
  • 577
  • 4
  • 11