How to make two events not fire at the same time

0

I need to make a menu that when I click the button it appears and when I click it it disappears. Home The problem I've been facing is that the event to make the menu disappear is the same as it appears, so it goes into a small loop. How do I not activate the two events at the same time?
HTML and JavaScript below.

$("#btn-menu").click(function (){
  $('.btn-menu').hide('slow');
  $('.div-nav-menu').show('slow');
});
$('body').click(function (){
  if(document.getElementById('1010').style.display == "block"){
    $('.div-nav-menu').hide('slow');
    $('.btn-menu').show('slow');
  }
  else{
    return (false);
  }
});
.div-nav-menu{
    border-radius: 50%;
    width: 500px;
    height: 500px;
    background-image: linear-gradient(65deg, #ff1414 15% , #002874 50%);
    position: fixed;
    z-index: 1000;
    top: -250px;
    right: -250px;
    display: none;
}
.btn-menu{
    width: 53px;
    height: 53px;
    background-image: linear-gradient(65deg, #ff1414, #002874);
    color: white;
    border-radius: 50%;
    border: none;
    margin-right: 260px;
    margin-top: 76px;
}
<div class="div-menu">
  <button class="btn-menu" id="btn-menu">menu</button>
  <div class="div-nav-menu" id="1010">
    <nav class="nav-menu">
      <ul>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
      </ul>
    </nav>
  </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    
asked by anonymous 05.09.2017 / 21:46

2 answers

3

I did not run your code here but from what I saw the following thing is happening.

In your code you have 2 event listeners. The first #btn-menu is bound to only the element with this id. The second 'body' is linked to the entire html page. Every event that occurs inside the body this second listener will catch. So whenever the first event occurs the second event will occur anyway.

You can do the following thing:

$('body').click(function (ev){
  if(document.getElementById('1010').style.display == "block" and ev.target.id != "btn-menu"){
    $('.div-nav-menu').hide('slow');
    $('.btn-menu').show('slow');
  }
  else{
    ev.preventDefault();
  }
});

In this case I check if the trigger the event was not the button and so I just disappear the menu if the click was not on the button.

Did you understand?

    
05.09.2017 / 22:26
1

Try to put the code e.stopImmediatePropagation (); in this form:

$("#btn-menu").click(function (e){

  e.stopImmediatePropagation();

});

So the other functions will stop running automatically.

    
05.09.2017 / 22:32