Frinsh
Frinsh

Reputation: 320

CSS3 Keyframe injected with javascript does not work with Chrome

I am creating a keyframe with javascript because I want to know a specific element's width in order to apply an animation style using that.

Here is the code:

var animation = false,
    animationstring = 'animation',
    prefix = '',
    domPrefixes = 'Webkit Moz O ms'.split(' '),
    pfx  = '',
    elm = document.querySelector('.marquee');

// Checks if the animation implementation is unprefixed
if( elm.style.animationName ) { animation = true; }

// Apply correct prefixes if the animation implementation has prefixes
if( animation === false ) {
    for( var i = 0; i < domPrefixes.length; i++ ) {
        if( elm.style[ domPrefixes[i] + 'AnimationName' ] !== undefined ) {
            pfx = domPrefixes[ i ];
            animationstring = pfx + 'Animation';
            prefix = '-' + pfx.toLowerCase() + '-';
            animation = true;
            break;
        }
    }
}

elm.style[ animationstring ] = 'marquee 20s linear infinite';
var keyframes = '@' + prefix + 'keyframes marquee { '+
    '0% { ' + prefix + 'transform: translateX(100%);}'+
    '100% { ' + prefix + 'transform: translateX(-' + elm.scrollWidth + 'px);}'+
    '}';

document.styleSheets[0].insertRule( keyframes, 0 );

http://jsfiddle.net/69PXa/

My problem (I think) is on row 27, I apply elm.scrollWidth as the value for translateX. This apparently breaks the keyframes in Chrome while it works as it should in Firefox. If I instead just use a fixed number the animation works.

Is there a way to solve this?

Upvotes: 1

Views: 847

Answers (2)

Daniel Perv&#225;n
Daniel Perv&#225;n

Reputation: 1716

You must apply the CSS to your .marquee after you define the actual keyframes. Right now you are telling the browser to animate using keyframes that don't exist yet.

JSFiddle

Upvotes: 1

Related Questions