Search code examples
jqueryfunctionasynchronouschaining

jQuery chain of functions


I have such html

<div class='mydiv expanded' id='1'>aaa</div>
<div class='mydiv ' id='2'>bbb</div>
<div class='mydiv ' id='3'>ccc</div>
<div class='mydiv ' id='4'>ddd</div>

and two functions:

function collapse(){
$(document).find('.expanded').removeClass('expanded')
}

function expand(itemid){
$(document).find('.mydiv[id="'+itemid+'"]').addClass('expanded');
}

From some other function I call

collapse() //i want to remove all classes "expanded"

expand(3) //i wand to add class "expanded" to an element with id 3

how can I call theese functions one after other - first collapse, then expand.

I have looked on deffered and $.when.then methods, but as I understood they ment to use with ajax calls...


Solution

  • JavaScript is interpreted and executed line-by-line. Just call your methods out in the order you want them to happen.

    $.when.then is needed when working with events, such as DOM or AJAX.