Online Promoters™ :: Web Development made simple

Setting & Getting background position with Prototype, Javascript

Getting the background position of a css element with prototype (javascript framework) is a bit tricky. Usually in all the good browser we refer to the background position of a css element by 'background-position'. As you probably know there usually is one shitty browser which always needs some "special attention" and several lines of code added just to work. Our today's example follows the pattern.
Internet Explorer does not understand the background-position as all the other browsers. For the x position we have to refer to it by 'background-position-x' and for the y position by background-position-y.
So, in order to get the background-position with prototype js and to have it working cross-browser you need to do something like this:

[sourcecode language="js"]
var divID = 'MyDivID';
var selector1 = 'background-position';
var selector2 = 'background-position-x';
var yourBackgroundPosition = $(divID).getStyle(selector1);
if(yourBackgroundPosition==undefined) var yourBackgroundPosition = $(divID).getStyle(selector2);
if(yourBackgroundPosition==undefined) return false;

Setting the css background position of an element with prototype's setStyle is done like this:
[sourcecode language="js"]
var divID = 'MyDivID';
var newval = '-250px';