android.nick
android.nick

Reputation: 11207

Jquery: is there a way to create functions in my small bit of code to make this faster/simplier/smaller?

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.

Upvotes: 1

Views: 70

Answers (2)

Blair McMillan
Blair McMillan

Reputation: 5349

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...

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630379

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.

Upvotes: 4

Related Questions