Linked Questions

Popular Questions

Make Jquery function wait for animation to finish

Asked by At

I know this has been asked a lot but I still can't seem to find an answer. I have two separate divs in my header and when one is clicked, it has some content fadeIn in the main part of my page. I'm trying to make it so that if one is already clicked, the new one has to wait for the old one to fadeOut before it fades in. My problem is that its not waiting for the old one to fadeOut, it's fading in right away. I left out the functions for page_2 but they're identical, just with the appropriate identifiers and variables switched.

var about_me_clicked = false;
var page_2_clicked = false;

$(document).ready(function() {
$('#About_me').click(about_me_clicked_func);
$('#Page_2').click(page_2_clicked_func);

var about_me_clicked_func = function() {  
  if(page_2_clicked){
      $.when(toggle_page_2()).done(toggle_about_me());
      page_2_clicked = !page_2_clicked;
  }
  else toggle_about_me();
  about_me_clicked = !about_me_clicked;
}

var toggle_about_me = function() {
  //do some formatting....
  if (!about_me_clicked) {
      return $('#About_me_main').fadeIn('slow').promise();
  }
  else return $('#About_me_main').fadeOut('slow').promise();

I tried using just .done() without the $.when() but that didn't work either. I also tried using a callback/complete function for fadeIn/fadeOut but I can't do that because there's a case where neither have been clicked (when the page first loads) so I wouldn't be able to pass in another function. Any help will be much appreciated, I've been stuck on this for days!

Related Questions