how can I stremline and consolidate this code?

how can I stremline and consolidate this code?

hi,

I have a standard nav show/hide feature in a mobile site...

basic code (questions inside code):


  1.   $('a#menu').click(function(e) {
        e.preventDefault();
        
        if (!$('#main_nav').is(':visible')) {
            $('#main_nav').fadeIn(1400);
            $(this).addClass('active');
            $('#wrapper').animate( { opacity:.4 }, 600);
            
        } else if ($('#main_nav').is(':visible')) {
        
        /*    following three lines the same as for
            $('#wrapper').click() below
            how do I do this w/o repeating this code?
        */
            $('#main_nav').fadeOut(1000);
            $(this).removeClass('active');
            $('#wrapper').animate( { opacity:1 }, 600);
        }
        
        /*
     (in case you were thinking of fn toggle(): (code below)
     I can't use this fn, b/c then, after I  close nav by clicking on the page(i.e., by activating $('#wrapper').click()), afterwards I have to hit the menu CTA twice to open the nav..  
      I have tested this again and again and can reproduce this behavior every time..)
        */
        
    });

        
    /*    if nav is open, click anywhere on pg to close it
    ****************************************************/

  2.     $('#wrapper').click(function() {
            if ($('#main_nav').is(':visible')) {        
                $('#main_nav').fadeOut(1000);
                $('a#menu').removeClass('active');
                $('#wrapper').animate( { opacity:1 }, 600);
            }
        });
        



    /*  version with fn toggle():
    ***********************************************/   

  1.     $('a#menu').toggle(
  2.         function(e) {
  3.             e.preventDefault();  //  do I need this here?
  4.             $('#main_nav').fadeIn(1400);
  5.             $(this).addClass('active');
  6.             $('#wrapper').animate( { opacity:.4 }, 600);
  7.         },
  8.         function(e) {
  9.             e.preventDefault();
  10.             $('#main_nav').fadeOut(1000);
  11.             $(this).removeClass('active');
  12.             $('#wrapper').animate( { opacity:1 }, 600);
  13.         }
  14.     );
  15.    
  16.     $('#wrapper').click(function() {
  17.         mainNav_pos = $('#main_nav').css('left');
  18.        
  19.         if ($('#main_nav').is(':visible')) {   
  20.             $('#main_nav').fadeOut(1000);
  21.             $('a#menu').removeClass('active');
  22.             $('#wrapper').animate( { opacity:1 }, 600);
  23.         }
  24.     });
  
 thank you....