1

I want to manipulate some attributes of my page elements in a java script function , take a look at this example and maybe you find a solution to do this.

function doubleup(attr){
attr*=2;
}
doubleup(myDIV.style.zIndex);
doubleup(myDIV.style.opacity);
pnuts
  • 58,317
  • 11
  • 87
  • 139
Amin Gholibeigian
  • 1,325
  • 2
  • 9
  • 11

2 Answers2

3

In short, you don't. You can't pass primitive values by reference. You can do that with non-primitive values, though, as they're always passed as reference. Example:

function doubleup(object, property) {
    object[propety] *= 2;
}
doubleup(myDiv.style, "zIndex");
doubleup(myDiv.style, "opacity");

Primitive data types are strings, numbers, booleans and, recently, Symbols

MaxArt
  • 22,200
  • 10
  • 82
  • 81
  • 1
    *"You can do that with non-primitive values, though"* No, you can't. "Pass by reference" is a specific term with a specific meaning: Passing a reference **to the variable** you're using when calling the function. (Which is, of course, a feature JavaScript doesn't have.) Passing an object reference is still pass by value (the value being the object reference). – T.J. Crowder Sep 19 '15 at 11:19
  • @T.J.Crowder Alright, you made a point. I just wrote that for the sake of simplicity, whereas it's more correct to say that non-primitive values are always referenced. – MaxArt Sep 19 '15 at 12:28
  • 1
    *Values* are never referenced in JavaScript; *objects* are referenced. Values are copied around -- between variables, when passing them into functions, coming out of functions, etc. One kind of value is a number. Another kind of value is an object reference. Objects are *not* values. – T.J. Crowder Sep 19 '15 at 12:35
  • @T.J.Crowder Fine, let's say non-primitive data types then. I don't know how that would help the point, though. – MaxArt Sep 19 '15 at 15:49
0

You only pass the value of this attribute to the function, so you don't change the style element, you only change the value, can do it in this way:

function doubleup(attr){
    return attr*=2;
}

myDIV.style.opacity = doubleup(myDIV.style.opacity);
myDIV.style.zIndex = doubleup(myDIV.style.zIndex);

By the way, you have to use zIndex instead of z-index to manipulate this value.

Another possible solution is:

function doubleup(el){
    el.style.opacity*=2;
}
function doubleupZIndex(el){
    el.style.zIndex*=2;
}

doubleupOpacity(myDIV);
doubleupZIndex(myDIV);
Sim
  • 3,279
  • 1
  • 17
  • 23