Search code examples
javascriptcssreplacevendor-prefix

using replace with browser prefixes js/css


I am making a javascript script that wants to do something like this:

elementObject.style.transform.replace('...','...');
elementObject.style.webkitTransform.replace('...','...');

And just to clear this up, yes, I have set both of those styles earlier in the script. However, this causes errors because in Chrome, for example, it does not recognize the transform style. Therefore, replace fails because elementObject.style.transform is undefined, and undefined has no method replace. Is there any way to do this without causing these errors? I just want the webkit transform, i do not need moz, o, or any other prefix.


Solution

  • var st = elementObject.style;
    if (st.transform !== undefined) st.transform = st.transform.replace('...','...');
    // ...
    

    or more general:

    function replaceStyle(element, style, text, replacement) {
      var vendors = ['webkit', 'moz', 'o', 'ms'];
      var st = element.style;
      if (st[style] !== undefined) st[style] = st[style].replace(text, replacement);
      style = style.charAt(0).toUpperCase()+style.substring(1);
      for (var i=0, l=vendors.length; i<l; i++) {
        var vendorStyle = vendors[i]+style;
        if (st[vendorStyle] !== undefined)
          st[vendorStyle] = st[vendorStyle].replace(text, replacement);
      }
    }
    
    // sample call (setting width from "40px" to "100%")
    replaceStyle( myElementObject, 'with', '40px', '100%' );