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?
-
2What do you mean wait until the width is 100%? Do you have some CSS transitions enabled? Otherwise this change is instant and there's no 'waiting' period.George– George2014年03月13日 20:14:32 +00:00Commented Mar 13, 2014 at 20:14
-
3Do you want to animate the css?j0hnstew– j0hnstew2014年03月13日 20:14:48 +00:00Commented Mar 13, 2014 at 20:14
-
possible duplicate of CSS3 transition eventsBlazemonger– Blazemonger2014年03月13日 20:15:23 +00:00Commented Mar 13, 2014 at 20:15
-
1@user3390776 You should really say that in your question it's not clear what you're looking for. Answer added none-the-less.George– George2014年03月13日 20:21:59 +00:00Commented Mar 13, 2014 at 20:21
-
1Define 'wait'. Are you wanting to animate the change to 100% width? Or is it just an instantaneous thing? If the latter, there is no need to wait.DA.– DA.2014年03月13日 20:28:51 +00:00Commented Mar 13, 2014 at 20:28
3 Answers 3
You can just use a timer to wait before processing some more code:
$('div').css('width', '100%');
setTimeout(function(){
$('div').css('color','red');
}, 2000);
7 Comments
Use jQuery animate()
$("div").animate({
width:"100%"
}, 2000, function() {
//On Animation complete
$('div').css('color', 'red');
});
Comments
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)