2 functions in javascript in the same div

Asked

Viewed 71 times

0

I have Ivs in my html code (there are 3 menu bars), when I click, it turns (as if it were an animation) into an x, however, I want when it turns and I click on it to perform another function other than the first one. An "openNav()" in the first and a "closeNav()" in the second, does anyone know a way? Using "onClick="

  function openNav() {
document.getElementById("mySidenav").style.width = "250px";
document.getElementById("main").style.marginLeft = "250px";
document.getElementById("t").onClick="closeNav()";

 }

 function closeNav() {
document.getElementById("mySidenav").style.width = "0";
document.getElementById("main").style.marginLeft = "0";
 }

 function myFunction(x) {
  x.classList.toggle("change");
 }



      <div id="t" class="container1" onclick="openNav()">
        <div class="container1" onclick="myFunction(this)" >
          <div class="bar1"></div>
          <div class="bar2"></div>
          <div class="bar3"></div>
      </div>
        </div>

1 answer

1


Can be easily solved by defining a global variable.

<script>
var open = true;

  function openNav() {
     document.getElementById("mySidenav").style.width = "250px";
     document.getElementById("main").style.marginLeft = "250px";
 }

 function closeNav() {
   document.getElementById("mySidenav").style.width = "0";
   document.getElementById("main").style.marginLeft = "0";
 }

 function myFunction(x) {
   x.classList.toggle("change");
   if(open){
     openNav();
     open = false;
   }else{
      closeNav();
      open = true;
   }
 }
</script>

Example of Logic: https://jsfiddle.net/u4rqyfxz/

  • It gives this error "Uncaught Typeerror: openNav is not a Function" despite being just before

  • @Pedrofreitas I think because the variable and Function have the same name. I changed and exemplified with an example.

  • Thanks! That’s right, thank you very much

  • 1

    Global variables are a bad solution. Use element attributes to make manipulation or encapsulate this in a IIFE. A solution without global variables: https://jsfiddle.net/u4rqyfxz/1/

Browser other questions tagged

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