Adam
Adam

Reputation: 1459

Issue with jQuery resize and if :visible.

I am creating responsive navigation and am experiencing an issue when resizing.

Here is a simplified codepen to illustrate the problem... http://codepen.io/anon/pen/xbEwmJ

When you start on a wide viewport (desktop view) and then resize down, you'll notice when you click on the hamburger icon, the menu slides down then slides straight back up again. This is not the behaviour I am after, the menu should only slide back up when the icon is clicked on again.

It works fine when you refresh the page on mobile view and then widen the browser window, so not sure why it does not work the other way.

I have a feeling it is to do with my if:visible statement?

Here is my code...

HTML

<header class="site-header cfix">
  <div class="wrap">
<nav class="cfix">
  <a class="toggleMenu" href="#">
    <span class="menuIcon" aria-hidden="true"></span>
        <span class="menuText">Menu</span>
  </a>
     <ul class="nav-pri nav1">
    <li><a class="js-toplink" href="#">Personal</a></li>
         <li><a class="js-toplink" href="#">Business</a></li>
     </ul>
     <ul class="nav-sec nav1">
       <li><a href="#">About</a></li>
         <li><a href="#">Claims</a></li>
         <li><a href="#">Contact</a></li>
     </ul>
</nav>
 </div>
</header>

Javascript

$(function(){

function checksize() {
  if ($(window).width() < 720) {
    $(".toggleMenu").click(function(){
        if ($(".nav1").is(':visible')) {
            $(".nav1").slideUp();
        } else {
            $(".nav1").slideDown();
        }
    });

} else {        
  $(".nav1").slideDown();   
}
}

checksize();

$(window).resize(checksize);

});

Upvotes: 0

Views: 108

Answers (1)

Shyam
Shyam

Reputation: 792

You are binding click event on .toggleMenu in a function, so everytime this function is run, like on on resize, it than again binds click event again, that is causing problem.

$(function(){
    $(".toggleMenu").click(function(){
        if ($(".nav1").is(':visible')) {
            $(".nav1").slideUp();
        } else {
            $(".nav1").slideDown();
        }
    });

    function checksize() {
        if ($(window).width() > 720) {
            $(".nav1").slideDown();
        }

        else{
            $(".nav1").hide(); // remove else condition if you want to show opend menu on shorter screen once clicked
        }
    }

    checksize();
    $(window).resize(checksize);
});

Upvotes: 2

Related Questions