0

I'm trying to get a CSS3 animation to animate every time a function is called.

My CSS code for the animation is in a class called 'enable' and it simply starts the animation.

My FUNCTIONS code is as follows:

document.getElementById("red").className = "enable";
    setTimeout(function() {
    document.getElementById("red").className = "";
}, 1000);

That works properly when using the setTimeout function but when i change the entire FUNCTIONS code to say like this:

document.getElementById("red").className = "";
document.getElementById("red").className = "enable";

It only works once.

Why can't I remove the class and then add it immediately after. Why doesn't my second code do the same thing as the first one?

Thanks in advanced!

2
  • 1
    No, I'd prefer if we used pure JavaScript please! Commented Jan 11, 2014 at 1:47
  • Hmmm, alright, I guess I will make do with setTimeout for now. If anyone else has a solution to effectively achieve this please provide it! Commented Jan 11, 2014 at 1:50

1 Answer 1

2

It may be helpful if included your html/css.

You have to use the setTimeout, otherwise the browser is not quick enough to pick up the change. Since javascript runs in a single thread, there is some breathing time needed for the browser to react to the change in class.

Here is an example: http://jsfiddle.net/brendonparker/75TfR

<!-- CSS -->
<style>
    #mydiv {
        -webkit-transition: all ease 1s;
        transition: all ease 1s;
    }

    #mydiv.enabled {
        background: red;
    }
</style>

<!-- HTML -->
<div id="mydiv" >
    <p>Hello World</p>
    <p>Test</p>
</div>

<!-- JS -->
<script>

    function animate(){
        var d = document.getElementById('mydiv');
        d.className = 'enabled';
        setTimeout(function(){ 
            d.className = '';
        }, 1000);
    }    

    animate();

</script>
Sign up to request clarification or add additional context in comments.

1 Comment

The beginning portion of your answer is exactly the answer to my question! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.