user1406271 user1406271 - 5 months ago 7x
jQuery Question

Detecting background image top margin with javascript

This is how I detect the top margin of a div and increase/decrease it:

var oldm = $("#bdi").css("margin-top").replace("px", "");

var addm = 1;

'margin-top': '-='+addm+'px'

But I need to do the same with background position.

  1. detect the actual top position of a background image

  2. increase/decrease the top margin of a background image

For example:

background-position: center 5px;

How do I detect "5px" and increase/decrease it?



As of jQuery 1.6, .css() accepts relative values similar to .animate(). Relative values are a string starting with += or -= to increment or decrement the current value. Link

For example like this

$("div").css("background-position-x", "+=10px");
$("div").css("background-position-Y", "-=10px");

If you want to do other operation on css value use this

$("div").css("background-position-x", function(index) {
    return index * 10;

You can see demo at bottom

    $("#image").css("background-position-x", "+=10px");
    $("#image").css("background-position-x", "-=10px");
    $("#image").css("background-position-y", "+=10px");
    $("#image").css("background-position-y", "-=10px");
#image {
    width: 100px;
    height: 100px;
    background-image: url("");
    background-position: 0px 0px;
<script src=""></script>
<div id="image"></div>
<button id="increaseX">increaseX</button>
<button id="decreaseX">decreaseX</button>
<br />
<button id="increaseY">increaseY</button>
<button id="decreaseY">decreaseY</button>

Firefox doesn't support background-position-x and background-position-y. If you want to do your target work in firefox, see jsfiddle

You can