Emily Schlenker
Emily Schlenker

Reputation: 1

click anywhere close menu; how do I make it stop opening when clicked anywhere

I have a menu that opens when a tab is clicked, and I made it so that when the viewer clicks anywhere on the webpage the menu will close again. However, the menu will also open when anywhere on the webpage is clicked. How do I make it so that clicking the tab is the only thing that will open the menu, and clicking the tab OR anywhere else will make it close?

This is what I have:

<script type="text/javascript">
    $(document).ready(function(){
        $("#bodyw2").click(function(){
            $(".panel").toggle("fast");
            $(".trigger").toggleClass("active");    
            return true;
        });
    });

    $(document).ready(function(){
        $(".trigger").click(function(){
            $(".panel").toggle("fast");
            $(this).toggleClass("active");  
            return false;
        });
    });
</script>

My website is http://www.drippydenton.net/ if there are any other questions as to what I'm talking about.

Upvotes: 0

Views: 347

Answers (2)

John Hunter
John Hunter

Reputation: 1

The simplest way to do this is to bind and unbind the click event for the body. Your code becomes:

$(document).ready(function(){
    $(".trigger").click(function(){
        $(".panel").toggle("fast");
        $(this).toggleClass("active");

        $("#bodyw2").click(function(){
            $(".panel").toggle("fast");
            $(".trigger").toggleClass("active");
            $("#bodyw2").unbind('click');
            return true;
        });

        return false;
    });
});

Upvotes: 0

bipen
bipen

Reputation: 36551

use hide() inside body click event .. instead of toggle().

  $(document).ready(function(){
   $("#bodyw2").click(function(){
      $(".panel").hide("fast");
      $(".trigger").removeClass("active");

      return true;
   });
    $(".trigger").click(function(){
      $(".panel").toggle("fast");
      $(this).toggleClass("active");

      return false;
    });
 });

and you don't need two document.ready function... add all codes inside one document.ready function

Upvotes: 4

Related Questions