Search code examples
javascriptjquerymethod-chaining

Why does chaining on multiple lines work in jquery?


I know that you can chain functions on an $( ) object with using dot notation e.g. $( ).delay().fadeIn().delay().fadeOut(), etc.

However this also works,

$( ).delay()
$( ).fadeIn()
$( ).delay()
$( ).fadeOut()

My intuition tells me that all methods should be independent, however they actually are sequential. I was curious if there was like a queue of functions inside the JQuery object that allowed this. Thanks,


Solution

  • delay(), fadeIn(), and fadeOut() all work by applying operations to the internal animation queue that jQuery maintains. As such, each call adds operations to the queue, and they (the queued operations) execute in the order they are added on the queue.

    http://api.jquery.com/delay/ makes reference to this queue as the second argument, which if not provided defaults to the fx queue.