Search code examples
menuslide

Close a sliding div by clicking outside of it


I spent hours to find a solution to my problem, but nothing worked yet :/

I made this pen which is working fine. It's a basic sliding menu with a open/close button (based on this jsfiddle) but I like to add a feature which allow users to close the menu by clicking anywhere outside of it.

Here is the code:

HTML

<div class='header'>
  <span class='button'>&#9776;</span>
  <span class="logo">LOGO HERE</span>
</div>
<div class='side-panel'>
  <nav>
    <ul>
      <li><a href='#'>ITEM 1</a></li>
      <li><a href='#'>ITEM 2</a></li>
      <li><a href='#'>ITEM 3</a></li>
    </ul>
  </nav>
</div>
<div class='content'>CONTENT HERE</div>

JS

$('.button').click(function(){
  if($(this).hasClass('active')){
    $(this).removeClass('active');
      $(this).html("&#9776;");
    $('.side-panel').animate({
    right:"-220px"
    });
    $(this).animate({
    right:"0"
    });
  }
  else{
    $(this).addClass('active');
    $(this).html("&#9587;");
    $('.side-panel').animate({
    right:"0",
  });
  $('.button').animate({
    right:"220px"
  });
  }
});

I found some very interesting topic here and I tried to add this :

$(document).click(function(){
  if ($('.button').hasClass('active')){
    $(this).removeClass('active');
  }
});

but doesn't worked. My knowledge with Js is basic (as my english (sorry)), and I'm pretty sure I'm not far from the solution but I spent already more than 3 hours and I'm starting to desperate ;) I hope I was clear enough but if you need more details, feel free to ask. Cheers, and thanks for your help.

CODEPEN


Solution

  • quick and dirty:

    act as if the button is pressed when you click on content:

    $('.content').click(
        function() { 
          $(".button").click(); 
        });
    

    better:

    extract the code from .button click event in a function and call that twice:

    $('.button').click(function(){
      showhide();
    });
    
    $('.content').click(function() { 
      showhide();
    });
    
    function showhide()
    {
      var $this = $(".button");
      if($this.hasClass('active')){
      $this.removeClass('active');
        $this.html("&#9776;");
      $('.side-panel').animate({
        right:"-220px"
      });
      $this.animate({
        right:"0"
      });
      }
      else{
      $this.addClass('active');
      $this.html("&#9587;");
      $('.side-panel').animate({
        right:"0",
      });
      $('.button').animate({
        right:"220px"
      });
      }
    }