user1406271 user1406271 - 6 months ago 11
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;

$("#bdi").css({
'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?

Thanks

Answer

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

$("#increaseX").click(function(){
    $("#image").css("background-position-x", "+=10px");
});
$("#decreaseX").click(function(){
    $("#image").css("background-position-x", "-=10px");
});
$("#increaseY").click(function(){
    $("#image").css("background-position-y", "+=10px");
});
$("#decreaseY").click(function(){
    $("#image").css("background-position-y", "-=10px");
});
#image {
    width: 100px;
    height: 100px;
    background-image: url("https://assets.servedby-buysellads.com/p/manage/asset/id/28536");
    background-position: 0px 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></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

Comments