0

I have a div like this:

<div style="width: 0%;"></div>

How can I change the css of width to 100% (and wait until it reaches 100%) before changing more elements?

For example:

$('div').css('width', '100%', function() {
    $('div').css('color', 'red');
});

Obviously this doesn't work, but how can I make it work?

DA.
  • 39,848
  • 49
  • 150
  • 213
user3390776
  • 61
  • 2
  • 7

3 Answers3

2

You can just use a timer to wait before processing some more code:

$('div').css('width', '100%');
setTimeout(function(){
    $('div').css('color','red');
}, 2000);

JSFiddle

George
  • 36,413
  • 9
  • 66
  • 103
  • I was going to say this doesn't handle the animation, but now that I re-read the question, I'm not sure animation is a part of the question. Hrm... – DA. Mar 13 '14 at 20:28
  • There's no mention of animation in the question, which is why I was a little confused by the other answers, I guess they are based on assumptions? This is based on the comment that the OP left. – George Mar 13 '14 at 20:29
  • Yea, I totally assumed an animation but that serves me right for not re-reading the question! :) – DA. Mar 13 '14 at 20:30
  • 1
    There's no waiting for anything to finish here... Should the question be, "How can I do something and then do something x seconds later?" – Ruan Mendes Mar 13 '14 at 20:42
  • @JuanMendes Probably, yeah. – George Mar 13 '14 at 20:45
  • @JuanMendes yes, it should! I tried to come up with a better title with the edit. – DA. Mar 14 '14 at 03:27
  • It happens all-too-often here. Not only do we work out the answers but also work out the question that the OP is trying to ask. It's part of what we (as answerers) do. – George Mar 14 '14 at 11:35
1

Use jQuery animate()

$("div").animate({
    width:"100%" 
  }, 2000, function() {
    //On Animation complete
    $('div').css('color', 'red');
  });

Fiddle

Eduardo Quintana
  • 2,368
  • 1
  • 15
  • 20
0

You can do it a number of ways. One way is to use CSS transitions:

.yourDiv {
    width: 0%;
    -webkit-transition: width;
    -webkit-transition-duration: 3s;
    background: yellow;
}

.yourDiv.wide {
    width: 100%;
}

Then, to animate, apply the class via jQuery:

$('.yourDiv').addClass('wide')

To do something after it's done animating, use the webkitTransitionEnd event:

$('.yourDiv')
    .addClass('wide')
    .one('webkitTransitionEnd', function(){
        $('this').css('background','red')
    })

If you wan to wait for a period of time after the animation finished before triggering your next style change, wrap it in a setTimeout:

var $yourDiv = $('.yourDiv')

$yourDiv
    .addClass('wide')
    .one('webkitTransitionEnd', function(){
            setTimeout(function(){
                $yourDiv.css('background','red')
            },2000)
    })

fiddle: http://jsfiddle.net/22fPQ/1/

(note the above is webkit-centric. Use other browser CSS prefixes as needed to support)

DA.
  • 39,848
  • 49
  • 150
  • 213