Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery background-position-x issue

How to do background-position-x in Jquery ?

console.log($('.element').css('background-position-x'));

Outputs (an empty string)

console.log($('.element').css('background-position'));

Outputs 0px 0px

What I want to do is:

$(this).css('background-position-x', '-162px');

How to make it work ?

Thank you very much.

like image 735
user1040899 Avatar asked Dec 17 '22 03:12

user1040899


2 Answers

Basically you get and set .css('backgroundPosition'), which is a string with a space seperating x and y, for example 12px 14px.

Tested in Firefox, Chrome/Safari, Opera, IE7, IE8:


Get it

If you want only background-position-x from jQuery:

var bpx = $('elem').css('backgroundPosition').split(' ')[0];

If you want only background-position-y from jQuery:

 var bpy = $('elem').css('backgroundPosition').split(' ')[1];

If you want both background-position-x and background-position-y from jQuery:

var bp = $('elem').css('backgroundPosition').split(' ');
var bpx = bp[0], bpy = bp[1];

Set it

(if you need animation, see Background Position animation in jQuery not working in Firefox)

To set background-position-x only without changing background-position-y:

var bpy = $('elem').css('backgroundPosition').split(' ')[1];
$('elem').css('backgroundPosition', '-192px ' + bpy);

To change or increment background-position-x only, based on its old value - for example, increase background-position-x by 5px:

(this simple example assumes it's a pixel value, and not something else like a percentage)

var bp = $('elem').css('backgroundPosition').split(' ');
var newBpx = (parseFloat(bp[0]) + 5) + 'px', bpy = bp[1];
$('elem').css('backgroundPosition', newBpx + ' ' + bpy );
like image 156
user56reinstatemonica8 Avatar answered Jan 01 '23 06:01

user56reinstatemonica8


background-position-x is not standard css and is not supoprted in all browsers. Take a look at solution at Background Position animation in jQuery not working in Firefox.

like image 30
elclanrs Avatar answered Jan 01 '23 06:01

elclanrs