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):
- $('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
****************************************************/
-
$('#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():
***********************************************/
- $('a#menu').toggle(
- function(e) {
- e.preventDefault(); // do I need this here?
- $('#main_nav').fadeIn(1400);
- $(this).addClass('active');
- $('#wrapper').animate( { opacity:.4 }, 600);
- },
- function(e) {
- e.preventDefault();
- $('#main_nav').fadeOut(1000);
- $(this).removeClass('active');
- $('#wrapper').animate( { opacity:1 }, 600);
- }
- );
-
- $('#wrapper').click(function() {
- mainNav_pos = $('#main_nav').css('left');
-
- if ($('#main_nav').is(':visible')) {
- $('#main_nav').fadeOut(1000);
- $('a#menu').removeClass('active');
- $('#wrapper').animate( { opacity:1 }, 600);
- }
- });
thank you....