Javascript only works after two clicks

2

I'm using a side menu on a website and wanted it retracted with a click of the button ... it just happens after two clicks !!

function resp() {

   var clique = document.getElementById("btn-menu");

   var menuLateral = document.getElementById("menu-lateral");



   clique.onclick = function (e) {

        e.preventDefault();

        menuLateral.classList.toggle('toggleMenu');

  };

}

I am using a link to call the script function: <a href="#" onClick="resp()" id="btn-menu">

  

side-menu is the div id of the side menu

     

toggleMenu is the class that is added to the side menu div

This code I took as the base of someone else, however it was not used as a function () and did not have an onClick in the tag ... however so mine does not work ... does anyone know what it can be ?? it is annoying to have to double-click the menu to retract (this only happens on the first touch after refreshing the page)

    
asked by anonymous 01.01.2018 / 00:22

2 answers

1

You do not need the resp() function and not even onClick in the element. Only the onclick = function event already captures the click and resolves the problem. As you are doing, you are calling two functions after the first click.

Using .onclick

var clique = document.getElementById("btn-menu");
var menuLateral = document.getElementById("menu-lateral");
clique.onclick = function (e) {
     e.preventDefault();
     menuLateral.classList.toggle('toggleMenu');
};
.toggleMenu{
   background: red;
}
<a href="#"  id="btn-menu">Menu</a>
<br />
<div id="menu-lateral">
   itens do menu
</div>

Using onclick

function resp() {
   var menuLateral = document.getElementById("menu-lateral");
   menuLateral.classList.toggle('toggleMenu');
}
.toggleMenu{
   background: red;
}
<a href="javascript:void(0)" onclick="resp()" id="btn-menu">Menu</a>
<br />
<div id="menu-lateral">
   itens do menu
</div>

Alternatively , you can call the direct function in href :

function resp() {
   var menuLateral = document.getElementById("menu-lateral");
   menuLateral.classList.toggle('toggleMenu');
}
.toggleMenu{
   background: red;
}
<a href="javascript:resp()" id="btn-menu">Menu</a>
<br />
<div id="menu-lateral">
   itens do menu
</div>
    
01.01.2018 / 00:33
1

It turns out that the way you're doing, you're calling the resp function and then assigning a new action to the btn-menu

You do not need to add the onclick event again.

<a href="#" onClick="return resp()" id="btn-menu">

function resp() {
   var menuLateral = document.getElementById("menu-lateral");
   menuLateral.classList.toggle('toggleMenu');

   return false;
}
    
01.01.2018 / 00:28