Skip to content

Instantly share code, notes, and snippets.

Created March 20, 2013 23:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/5209525 to your computer and use it in GitHub Desktop.
Save anonymous/5209525 to your computer and use it in GitHub Desktop.
jQuery CSS hook for background-position-x/y
(function($) {
// backgroundPosition[X,Y] get hooks
var $div = $('<div style="background-position: 3px 5px">');
$.support.backgroundPosition = $div.css('backgroundPosition') === "3px 5px" ? true : false;
$.support.backgroundPositionXY = $div.css('backgroundPositionX') === "3px" ? true : false;
$div = null;
var xy = ["X","Y"];
// helper function to parse out the X and Y values from backgroundPosition
function parseBgPos(bgPos) {
var parts = bgPos.split(/\s/),
values = {
"X": parts[0],
"Y": parts[1]
};
return values;
}
if (!$.support.backgroundPosition && $.support.backgroundPositionXY) {
$.cssHooks.backgroundPosition = {
get: function( elem, computed, extra ) {
return $.map(xy, function( l, i ) {
return $.css(elem, "backgroundPosition" + l);
}).join(" ");
},
set: function( elem, value ) {
$.each(xy, function( i, l ) {
var values = parseBgPos(value);
elem.style[ "backgroundPosition" + l ] = values[ l ];
});
}
};
}
if ($.support.backgroundPosition && !$.support.backgroundPositionXY) {
$.each(xy, function( i, l ) {
$.cssHooks[ "backgroundPosition" + l ] = {
get: function( elem, computed, extra ) {
var values = parseBgPos( $.css(elem, "backgroundPosition") );
return values[ l ];
},
set: function( elem, value ) {
var values = parseBgPos( $.css(elem, "backgroundPosition") ),
isX = l === "X";
elem.style.backgroundPosition = (isX ? value : values[ "X" ]) + " " +
(isX ? values[ "Y" ] : value);
}
};
$.fx.step[ "backgroundPosition" + l ] = function( fx ) {
$.cssHooks[ "backgroundPosition" + l ].set( fx.elem, fx.now + fx.unit );
};
});
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment