0

I am currently trying to animate two div elements in a carousel-type container. Here is the markup as it appears in the DOM:

<div id="transitioner" style="width: 2880px; height: 775px; left: -1440px; ">
    <div id="view1" class="view active" style="width: 1440px; height: 775px; ">
        <header>
            <h1>This is page 1</h1>
        </header>
        <article style="height: 699px; ">
            <p>Tap me anywhere to go to the next view</p>
        </article>
        <footer>
            <p>This is my footer</p>
        </footer>    
    </div>
    <div id="view2" class="view" style="width: 1440px; height: 775px; ">
        <header style="">
            <h1>This is page 2</h1>
        </header>
    </div>
</div>

And here is the CSS for the #transitioner element:

#transitioner {
    position: absolute;
    top: 0;
    -webkit-transition: all 0.2s ease-in-out;
}

Finally, the JS:

function GotoView(view)
{
    var roller = $('<div id="transitioner" />');
    roller.width((viewport.width * 2)).height(viewport.height);
    var current = $('.view.active').clone(true, true);
    $('.view.active').remove();
    current.prependTo(roller);

    var new_view = view.clone(true, true);
    view.remove();
    new_view.appendTo(roller);

    roller.appendTo($('body'));
    $('body').addClass('transitioning');
    //window.setTimeout(function() { roller.css({ left: 0 - viewport.width }) }, 2000);
    roller.css({ left: 0 - viewport.width });
}

I update the left position of the containing div (i.e. #transitioner), but unless I put in a setTimeout, the CSS transition does not execute, rather the containing div simply 'jumps' to the desired new left offset.

I have put together a jsFiddle so you can see the symptoms > http://jsfiddle.net/XPUPQ/

My question is: what is this happening, and short of using the JS setTimeout() is there any way to circumvent this?

1 Answer 1

5

You need to trigger a browser reflow

http://jsfiddle.net/XPUPQ/1/

You could do that with $("body")[0].offsetWidth; for example.

This is actually a legit technique that twitter bootstrap uses for example

Sign up to request clarification or add additional context in comments.

4 Comments

Why do I say "for example" too much
Sounds better than 'perkele'.
Hehe thanks for the help, never come across this bug before and didn't know that caused a browser reflow. Any idea why we need to do this?
@BenM Because browsers optimize too much :P Maybe this helps though stackoverflow.com/a/6496557/995876

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.