Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a variable to the style property in javascript?

I'm sorry if the question is phrased with the incorrect terminology.

Basically I want to specify what style I want to change in a function by passing it a variable.

function styleChanger(ele, styleProp, x){
      ele.style.styleProp = x + "px";
}

var box = document.getElementById("box");
var height = 100;
var width = 100;
var top = 500;
var styleProp = [height,width,top];

styleChanger(box, styleProp[0], height);
styleChanger(box, styleProp[1], width);
styleChanger(box, styleProp[2], top); 

I want to do this but its not possible, is there a way?

like image 882
Tanil Avatar asked Dec 29 '25 10:12

Tanil


1 Answers

On this line:

var styleProp = [height,width,top];

I think you meant:

var styleProp = ["height","width","top"];

If so: In JavaScript, you can refer to a property either using dotted notation and a literal property name (obj.foo), or using bracketed notation and a string property name (obj["foo"]). In the latter case, of course, you can use any expression that evaluates to a string, including a variable reference.

So within styleChanger, you can use bracketed notation:

ele.style[styleProp] = x + "px";
//        ^------- Not the same `styleProp` as above; this one is
//                 the arg to the `styleChanger` function

Because of the styleProp confusion, here's a complete example with the name of the array changed:

function styleChanger(ele, styleProp, x){
      ele.style[styleProp] = x + "px";
      //       ^----------- bracketed notation
}

var box = document.getElementById("box");
var height = 100;
var width = 100;
var top = 500;
var styleNames = ["height","width","top"];

styleChanger(box, styleNames[0], height);
styleChanger(box, styleNames[1], width);
styleChanger(box, styleNames[2], top); 
like image 162
T.J. Crowder Avatar answered Dec 30 '25 22:12

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!