vlada vlada -4 years ago 153
CSS Question

Jquery Menu slide in on click

I have a little problem with my menu.

This is the situation:

$(document).ready(function (){
$('.btn').click(function (){

<button class="btn">Menu</button>
<div class="div1">some content</div>

This is what I have for now. So, I have that on button click, div fades in. But, I just can't do the next step. I want now that this 'div1' fades out on click anywhere else on the page, just not on that div and button.

I click on 'btn', 'div1' shows up on the screen, then I move a mouse outside that 'div1' area and click anywhere else on the page, then 'div1' fades out (hide).

Can someone helps me with that please?


Answer Source

Make the div focusable with tabindex="-1", then add an .on('blur', function() {}) event to the div (and remove the focus outline with css):

$('.btn').on('click', function() {

$('.div1').on('blur', function() {
.div1 {
  background-color: #eee;
  padding: 1em;
  display: none;
  outline: none;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn">Menu</button>
<div class="div1" tabindex="-1">some content</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download