Rohit Kumar
Rohit Kumar

Reputation: 2031

Javascript code for CSS3 animation and transform property

I know, with CSS, we have to use vendor prefixes such as -ms-, -moz-, -webkit- and -o- for transform property. And for animation property just -moz-, -webkit- and -o-. I want to know how to set each of them from Javascript? And transition property also.

Looking for something like this -

object.style.vendorTransform     // whole list
object.style.vendorAnimation     // whole list
object.style.vendorTransition    // whole list

Thanks in advance.

Note- I don't need any plugin, I need the pure Javascript code.

Upvotes: 2

Views: 446

Answers (3)

frontend_dev
frontend_dev

Reputation: 1719

When I understand your question correctly you want to do the transform in JS, and not CSS (in that case I'd recommend SASS with the compass framework)

You could do it like this, so the right prefix is used:

var sty = ele.style, transform, transforms = ["webkitTransform", "MozTransform", "msTransform", "OTransform", "transform"];
for (var i in transforms) {
    if (transforms[i] in sty) {
        transform = transforms[i];
        break;
    }
}

and later on:

ele.style[transform] = "whatever transform you like to do";

So you do not have to set each of them, and of course you can reuse the "transform" variable for other elements, so the check only has to be done once.

Upvotes: 2

haravares
haravares

Reputation: 542

Try something like this:

// es6
function animate(element, transformValue = 'none', transitionValue = 'none') {
  const prefixes = ['webkit', 'moz', 'ms', 'o', '']

  if (element) {
    for (let value of prefixes) {    
      element.style[value + 'Transform'] = transformValue
      element.style[value + 'Transition'] = transitionValue
    }
  }
}

const el = document.getElementById('someId')
animate(el, 'translate3d(200px, 0, 0)', 'transform 400ms ease-out')

Upvotes: 0

aredzko
aredzko

Reputation: 1730

Less is a pretty neat JavaScript tool you can use to do this.

Upvotes: 0

Related Questions