3

I wanted to close the mobile navbar on click, I see the answer for my question here. The problem with the code given in this question is that it's always trying to close the navbar, no matter if we see the toggle navbar or the "Normal" navbar. So I want to do an if/else that check if the width is higher or lower that 768px (the width that changes the navbars), so I have this in my document.ready() right now.

 function close_toggle() {
   if ($(window).width() <= 768) {

    $('.nav a').on('click', function(){
        $(".navbar-toggle").click();
    });
 } 
}
close_toggle();

$(window).resize(close_toggle);

The problem with this code is that if I start with a width higher than 768px and go to less than 768px all works good. But if I start with a width lower that 768px when I resize to higher that 768px the normal navbar will blink when I click in the links (because is closing the toggle menu, I think).

So I need an else statement to reverse the if code, but I don't know how to reverse that code. Please sorry for some English errors. Hope someone could help me.

Community
  • 1
  • 1
luidgi27
  • 324
  • 2
  • 15

1 Answers1

7

Look if it helps:

 function close_toggle() {
   if ($(window).width() <= 768) {
      $('.nav a').on('click', function(){
          $(".navbar-toggle").click();
      });
   }
   else {
     $('.nav a').off('click');
   }
}
close_toggle();

$(window).resize(close_toggle);
Paulo Roberto Rosa
  • 3,071
  • 5
  • 28
  • 53
  • 1
    Thank you so much ! It gave me a problem with the code of the smooth scroll but it's already resolved :) Know I just need to update this to don't close automatically when it's a dropdown, but shouldn't be a problem. – luidgi27 Nov 08 '13 at 12:19
  • @Paulo Roberto, Thanks for the solution. I'm curious... How do we know that ".navbar-toggle" has a method click() that would close it? – ayjay May 07 '14 at 16:53
  • That will *Toggle* it. In the case, will close. The method .click() is a jQuery method, and the event bound to it, is from Bootstrap behaviour. – Paulo Roberto Rosa May 07 '14 at 20:23