Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all background properties using javascript/jquery

I have an element like:

<div style="background-color: #ffffff; background-image: url(image.jpg);></div>

The background properties are being set using jquery like so:

$('div').css('background-color', '#ffffff');

Once the various properties have been set I want to get them all out as a shorthand declaration. I was hoping that just by doing:

var background = $('div').css('background');

would work however it doesnt seem to.

Anybody got a solution to this?

The only thing I can come up with is doing string concatenation such as:

var background = $('div').css('background-color') + ' ' + $('div').css('background-image');

however this will be very messy and rquire a lot of checks as not all background variables are always set, such as position etc.

any thoughts how this can be done would be greatly appreciated!

like image 557
Mike Oram Avatar asked Oct 01 '22 22:10

Mike Oram


2 Answers

You can pass an array to the .css() method, and it'll return you an array object with the values of all the properties you asked for.

var backgroundStuff = [
  "background-color",
  "background-position",
  "background-repeat",
  // ...
];

var props = $(whatever).css( backgroundStuff );
alert(props["background-color"]); // whatever the background color is

This is a fairly new feature (version 1.9).

like image 91
Pointy Avatar answered Oct 07 '22 23:10

Pointy


Seeing as there does not appear to be a reliable cross browser solution to this, I have done the following to get around the problem.

I have set up an object like so:

var backgroundDefaults = {
    color: "#ffffff",
    image: "none",
    repeat: "repeat",
    position: "top left"
}

When the user changes one background property, such as the background colour, I use the object to set all the defaults on the element. By doing this it ensures that all the values that can be changed are always set and so I can reliably get them off the element using:

var background = $('div').css('background-color') + ' ' + $('div').css('background-image');

as mentioned in the original question.

like image 1
Mike Oram Avatar answered Oct 07 '22 22:10

Mike Oram