3

If I assume that the background position will always be in the format:

0px 0px; or 10px 11px; So, *number*px *number*px.

How can I get both the x position and the y position in Javascript?

Hommer Smith
  • 26,772
  • 56
  • 167
  • 296

1 Answers1

13

Given the following HTML:

<div id="demo"></div>

And CSS:

div {
    height: 500px;
    width: 500px;
    margin: 0 auto;
    background: #fff url(http://placekitten.com/300/300) 50% 50% no-repeat;
}

The following JavaScript works:

var demo = document.getElementById('demo'),
    _tmp = window.getComputedStyle(demo,null).backgroundPosition.trim().split(/\s+/),
    positions = {
        'left' : _tmp[0],
        'top' : _tmp[1]
    };
console.log(positions, positions.left, positions.top);

JS Fiddle demo.

The above approach does require a browser that supports window.getComputedStyle() (obviously), and trim() (though that could be replaced with a replace(/^\s+|\s+$/g,'')).

To get access to the units, and numbers, independently I'd suggest creating other objects within the overall object to hold those numbers, and units:

var demo = document.getElementById('demo'),
    _tmp = window.getComputedStyle(demo,null).backgroundPosition.trim().split(/\s+/),
    positions = {
        'left' : _tmp[0],
        'top' : _tmp[1],
        'numbers' : {
            'left' : parseFloat(_tmp[0]),
            'top' : parseFloat(_tmp[1])
        },
        'units' : {
            'left' : _tmp[0].replace(/\d+/,''),
            'top' : _tmp[1].replace(/\d+/,'')
        }
    };
console.log(positions, positions.left, positions.top, positions.numbers.left, positions.numbers.top, positions.units.left, positions.units.top);

JS Fiddle demo.

As to what would happen if there was no background-position set? Well, why not try that, with the following CSS:

div {
    height: 500px;
    width: 500px;
    margin: 0 auto;
    background-color: #fff;
    background-image: url(http://placekitten.com/300/300);
    background-repeat: no-repeat;
}

In Chromium it seems that you get the default background-position of 0% 0% (and corresponding numbers and units): JS Fiddle demo.

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • This is what I was looking for. However, if I wanted to get the values and units separately, how could I do it? I mean, if I needed to know the value to do some calculus and then the units? – Hommer Smith Oct 21 '13 at 21:56
  • Also, what would happen if the element does not have a background-position attribute? What would this do: window.getComputedStyle(demo,null).backgroundPosition – Hommer Smith Oct 21 '13 at 21:59
  • See the updates, I think I've answered those questions adequately? – David Thomas Oct 21 '13 at 22:05