Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to set style using pure javascript?

Tags:

javascript

What is the most efficient way to set multiple styling on elements in javascript?

for (i=0;i<=lastSelector;i++) {
var e = mySelector[i],
v = 'opacity 1s';
e.style.WebkitTransition = v;
e.style.MozTransition = v;
e.style.OTransition = v;
e.style.MsTransition = v;
e.style.transition = v;
e.style.opacity = 0;
};
like image 644
Hakan Avatar asked Jan 05 '12 13:01

Hakan


1 Answers

Pretty much that, you could use a stacked assignment:

for (i=0;i<=lastSelector;i++) {
  var e = mySelector[i];
  e.style.WebkitTransition =
    e.style.MozTransition =
      e.style.OTransition =
        e.style.MsTransition =
          e.style.transition =
            'opacity 1s';
  e.style.opacity = 0;
}

Since there are several of these properties where we have vendor-specific versions, you might consider a reusable function that does this, e.g.:

function setMultiVendorProp(style, propName, value) {
    // Set the non-vendor version
    style[propName] = value;

    // Make first char capped
    propName = propName.substring(0, 1).toUpperCase() + propName.substring(1);

    // Set vendor versions
    style["Webkit" + propName] = value;
    style["Moz" + propName] = value;
    style["O" + propName] = value;
    style["Ms" + propName] = value;

    // Done
    return value;
}

Or using the dashed style instead, since we're already using strings rather than identifiers:

function setMultiVendorProp(style, propName, value) {
    // Set the non-vendor version
    style[propName] = value;

    // Set vendor versions
    style["-webkit-" + propName] = value;
    style["-moz-" + propName] = value;
    style["-o-" + propName] = value;
    style["-ms-" + propName] = value;

    // Done
    return value;
}

Then:

for (i=0;i<=lastSelector;i++) {
  var e = mySelector[i];
  setMultiVendorProp(e.style, "transition", "opacity 1s");
  e.style.opacity = 0;
}

Side notes:

  • There's no ; after the closing } in a for statement.
  • var anywhere in a function is function-wide, so declaring var within non-function blocks inside the function is (slightly) misleading to the reader of the code; details: Poor, misunderstood var
like image 197
T.J. Crowder Avatar answered Oct 02 '22 12:10

T.J. Crowder