curly_brackets
curly_brackets

Reputation: 5598

Background-position +/- X pixels

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

Upvotes: 2

Views: 2345

Answers (3)

andyb
andyb

Reputation: 43823

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');

Upvotes: 1

Rebecca
Rebecca

Reputation: 587

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

Upvotes: 0

amosrivera
amosrivera

Reputation: 26514

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/

Upvotes: 1

Related Questions