gomangomango
gomangomango

Reputation: 691

Run a line of jQuery after the previous one is complete

I have two lines of jQuery and I need one to run after the previous one is complete.

I know js is read line by line, but the second line is happening too soon.

I can't use jQuery callbacks because these functions unfortunately don't have them.

I tried doing a setTimeout() with a wait for 500ms, 1000ms, and 1600ms, but it didn't seem to work. Visually, the second line took place before the first line was completed.

The element used in the first selector has a css transition of 1s and I want that to finish and then the second line to take place.

Is it possible to do something like:

if transition complete, run js else wait, then check if transition complete, then if true run js.

Here are the two lines of js:

$('#searchInput').removeClass('slideBack').css('top', 0);
$('#headerTopBar').css('position', 'relative').hide();

Upvotes: 2

Views: 1970

Answers (2)

jfriend00
jfriend00

Reputation: 707328

If you want to wait for a CSS transition to complete, then you need to use an eventListener for the CSS transitionend event on the object that is doing the transition. That will then provide an event handler callback where you can carry out the second line of code after the CSS transition completes.

$('#searchInput').one("transitionend", function(e) {
    $('#headerTopBar').css('position', 'relative').hide();
}).removeClass('slideBack').css('top', 0);

Now, in the real world, not every browser uses the same event name for the transition end event so one typically either installs event handlers for all the possible names of the transition end event or one in your code figure out which name is used in this local browser and then use that variable as the event name.

Note: I use .one() so that this event handler will automatically uninstall itself after it fires. I don't know for sure you want that, but it is often desirable with these types of event notifications.

Here's a more verbose version that listens for all possible transition end event names (for all major browsers):

$('#searchInput').one("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(e) {
    $('#headerTopBar').css('position', 'relative').hide();
}).removeClass('slideBack').css('top', 0);

Upvotes: 1

Felix
Felix

Reputation: 38102

.css() does not take a callback, you can use .animate() instead:

$('#searchInput').removeClass('slideBack').animate({top:0},500,function () {
    $('#headerTopBar').css('position', 'relative').hide();
});

Upvotes: 0

Related Questions