10

I am looking to use Webkit CSS3 to move a absolutely positioned DIV from one location to another on the screen when a button is pressed, by changing its left and right CSS properties. However, all the examples for doing this that I saw use a static CSS rule to apply this transition.

I don't know the new position before hand, so how do I apply this CSS3 transition dynamically?

2 Answers 2

21

Once you've defined the transition it will apply no matter how you change the CSS values on the element. So you can just apply an inline style with JavaScript and the element will animate. So with CSS like this:

left: 100px;
top: 100px;
-webkit-transition: top 300ms ease-in 100ms, left 200ms ease-in 50ms;
-moz-transition: top 300ms ease-in 100ms, left 200ms ease-in 50ms;
-o-transition: top 300ms ease-in 100ms, left 200ms ease-in 50ms;
transition: top 300ms ease-in 100ms, left 200ms ease-in 50ms;

Have a function like this:

function clickme() {
    var el = document.getElementById('mydiv');
    var left =  300;
    var top =  200;
    el.setAttribute("style","left: " + left + "px; top: " + top + "px;");
}

And you will see the animation when you call the function. You can get the values for left and top from where ever you like. I've done a full example.

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

5 Comments

Nice complete answer and demo! Great resource for CSS3 animation explorers.
Thanks @Todd - I try to make my answers worthwhile :)
isn't it easier to toggle a class with associated animation?
@Vprimachenko in this case you'd have to create a class for each of the possible combinations of left and top, then pick the right one depending on the values entered, so no
oh i see i misunderstood the requirements, thanks for clarification
0

Another option would be to use jQuery Transit to move the absolutely positioned div left or right:

Javascript:

$("#btnMoveRight").click( function () {
    $('#element').transition({ left: '+=50px' });
});

$("#btnMoveLeft").click( function () {
    $('#element').transition({ left: '-=50px' });
});

JS Fiddle Demo

It works well on mobile devices and handles your CSS3/browser compatibilities for you.

Comments

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.