0

How can I add a class to a div, wait a second, remove the class, then add another?

$(".bauble_01").toggleClass("sway-left").delay(1000).toggleClass("sway-right");

I was hoping the above would add "sway-left", wait a second, then remove "sway-left" and add "sway-right" but it does it at the same time... the delay doesn't seem to work?

What am I doing wrong?

dubbs
  • 1,167
  • 2
  • 13
  • 34
  • The duplicate will help you understand why `delay()` does not behave as you expect, but note your current code does not remove the `sway-left` class either. – Frédéric Hamidi Dec 05 '16 at 16:44
  • `toggleClass` isnt queued, use [`queue`](https://api.jquery.com/jQuery.queue/) – Jamiec Dec 05 '16 at 16:44
  • You can also utilize `.promise()`, `.then()`, `setTimeout()` or `.animate()` to achieve expected result. – guest271314 Dec 05 '16 at 16:47
  • @FrédéricHamidi Note, linked Question and Answer does not actually describe how to solve current Question using `.queue()` and `.delay()` without an animation queue. – guest271314 Dec 05 '16 at 16:52
  • 1
    @guest, it does explain how to use delay() to introduce an actual delay between two synchronous operations, though. Of course, if you find a more appropriate duplicate, feel free to suggest it. – Frédéric Hamidi Dec 05 '16 at 16:57
  • @FrédéricHamidi Providing a name for the queue at `.delay()`, `.queue()` allows functions to be queued without using default `"fx"` animation queue http://stackoverflow.com/a/30001155/ – guest271314 Dec 05 '16 at 17:05
  • Ok thanks - all - I didnt really understand these comments - but got it working with a setTimeout to call the 2nd toggle function after the first. Works well: – dubbs Dec 05 '16 at 18:05

0 Answers0