vlada vlada - 24 days ago 6
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 (){
$('.div1').fadeIn();
});
})

<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.

Example:
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?

Tnx

Answer

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').fadeIn();
  $('.div1').focus();
});

$('.div1').on('blur', function() {
  $(this).fadeOut();
});
.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>

Comments