views:

36

answers:

2

I'm trying to find a way to make this smaller by using functions/variables in my jquery.

$('.search-what-category').fadeOut('normal', function(){  
  $('.search-wrapper').animate({'height':40})  
})


$('.search-what-category').fadeOut('normal', function(){    
  $('.search-wrapper').animate({'height':40}, function(){
    $('.search-wrapper').animate({'top':-60})
}) 

I can create the first snippet into a function, but the second snippet has an extra line in it (see the first and the second snippets are the same but the second one has an extra line of code). How would I create a function for the first snippet, and then be able to add into it the extra line shown in the second snippet? This is what I tried:

function hidecat(){
  $('.search-what-category').fadeOut('normal', function(){  
    $('.search-wrapper').animate({'height':40})  
  })
}

hidecat($('.search-wrapper').animate({'top':-60}))

but that doesn't seem to work. I want the hidecat() function to activate and then when it's done, to activate the extra line of code, like in my example directly above this.

+4  A: 

You need to allow yourself to pass a callback, like this:

function hidecat(callback){
  $('.search-what-category').fadeOut('normal', function(){  
    $('.search-wrapper').animate({'height':40}, callback);
  })
}

Then pass to that parameter and anonymous function (which will be called when the first animation completes):

hidecat(function() { $(this).animate({'top':-60}); });

Or, if it's always an animation, just pass the options:

function hidecat(opt){
  $('.search-what-category').fadeOut('normal', function(){  
    var sw = $('.search-wrapper').animate({'height':40});
    if(opt) sw.animate(opt);
  })
}

hidecat({'top':-60});

The if() check allows you to just call hidecat(); without any options as well, which would run nothing after the height animation.

Nick Craver
Ahh, your way is so much nicer. Stop being so smart!
Blair McMillan
A: 

What about:

function hidecat(callback){
  $('.search-what-category').fadeOut('normal', function(){  
    $('.search-wrapper').animate({'height':40})  
  })

  function() {callback}
}

hidecat($('.search-wrapper').animate({'top':-60}))

I think that works...

Blair McMillan