JavaScript, jQuery, CSS and the background-position attribute

September 2010

The jQuery .css() function allows one to retrieve an existing value from, or set a new value to, the DOM element(s) you specify.

Of course, you don't need jQuery to do this but this is my website, and I like it, so there. Everything about this function works exactly as it says on the tin except, I've found, when retrieving the background-position attribute in pre-IE9 Internet Explorer.

In any other browser, I'm returned a string holding the x- and y-coordinate values, such as "100px 200px". Internet Explorer returns an unhelpful undefined. This is because, while you can set background-position in IE, it appears to me that you can only retrieve the values background-position-x and background-position-y.

Below is a tiny function that fixes this problem, returning, regardless of (modern) browser, an object containing the x- and y-coordinates and their unit of measurement.

function GetBackgroundImagePos(v) {
    var vResult = $(v).css("background-position");
    if (typeof vResult == "string") {
        var a = vResult.split(" ");
    } else {
        var a = [$(v).css("background-position-x"),
                 $(v).css("background-position-y")];
    }
    return {
        x: parseFloat(a[0]),
        xUnit: a[0].replace(/[0-9-.]/g, ""),
        y: parseFloat(a[1]),
        yUnit: a[1].replace(/[0-9-.]/g, "")
    };
}

This will return, for example:

{ x: 200, xUnit: "px", y: 50, yUnit: "%" }

Frustratingly, Internet Explorer chooses to convert "%" and "em" values to "px". Firefox preserves "%" but does the same thing as IE with "em" measurements. I can see why they'd do this, but I don't see it as being particularly helpful to the poor web developer trying to create a cross-browser experience.

Jon Combe