How to make two events not fire at the same time

Asked

Viewed 113 times

0

I need to make a menu that when you click the button it appears and when you click outside it disappears.
The problem I’ve been facing is that the event to make the menu disappear is what becomes the same as appearing, so it enters a small loop.
How to do not activate both 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>

2 answers

3


I haven’t circled your code here but from what I’ve seen is going on the following thing.

In your code you have 2 Event listeners. The first #btn-menu is linked only to the element with that id. The second body is linked to every html page. Every event that occurs inside the body that second Istener will pick up. So whenever the first event occurs the second 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 who triggered the event was not the button and so I only disappear the menu if the click was not on the button.

It seemed?

  • You did. I’ll check and get back to you.

1

Try placing the e.stopImmediatePropagation() code in this form:

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

  e.stopImmediatePropagation();

});

So the other functions will stop running automatically.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.