Javascript only works after two clicks

Asked

Viewed 1,261 times

2

I’m using a side menu on a site and I wanted it to retract with a click on the button... it turns out it’s only happening 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’m using a link to call the script function: <a href="#" onClick="resp()" id="btn-menu">

side menu is the id of the side menu div

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

This code I took as someone else’s base, but she didn’t use as Function() and didn’t have an onClick in the tag ... but so mine doesn’t work... does anyone know what it might be?? it’s annoying to have to double-click the retract menu (this only happens at the first touch after updating the page)

  • Please mark one of the answers with . It doesn’t have to be mine, but it’s very important to mark an answer that helped you or report what didn’t help. Obg!

2 answers

1

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

You don’t need to add the event onclick again.

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

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

   return false;
}

1


You don’t need the function resp() and not even the onClick element. Only the event onclick = function already captures the click and solves the problem. The way 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 function direct on 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>

Browser other questions tagged

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