Question

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.

Was it helpful?

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%' );

OTHER TIPS

You must use the Adapter design pattern.

For example:

function transformStyle() {
    var tempEl = document.createElement('div'),
        elStyle = tempEl.style;

    if (typeof elStyle.transform !== 'undefined') {
        transformStyle = function (el, val) {
            val != null && (el.style.transform = val);
            return el.style.transform;
        };
    } else if (typeof elStyle.webkitTransform !== 'undefined') {
        transformStyle = function (el, val) {
            val != null && (el.style.webkitTransform = val);
            return el.style.webkitTransform;
        };
    } else {
        transformStyle = function () { return ''; }; //ignore when not supported
    }

    tempEl = null;
    elStyle = null;

    return transformStyle.apply(this, arguments);
}

var el = document.createElement('div');

transformStyle(el, 'rotate(-2deg)'); //set style
transformStyle(el); //rotate(-2deg)

Obviously you could write something more generic such as a style method that allows accessing or modifying any styles. You could use a list of vendor prefixes to make the code more DRY as well. The previous code was just an example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top