Error "toggle is not defined"

1

I have the following concern: My code works, but when I see the console it throws "ReferenceError: toggle is not defined"

Here I leave the code

<div class="container-menu" id="icon-menu">
    <div class="bar-1"></div>
    <div class="bar-2"></div>
    <div class="bar-3"></div>
</div>


window.onload = function(){ 

    var icoMenu = document.getElementById('icon-menu');

    icoMenu.onclick = function myFunction() {
        icoMenu.classList.toggle('changeMenu');
    }
    icoMenu.addEventListener('click', toggle, false);   

};

Any solution?

    
asked by DCdesign 29.11.2016 в 15:53
source

1 answer

0
  

The error is that the function toggle is not defined.

When you see your code, there is something that seems to be over ... why?

  • Assignments to icoMenu in onclick , execute myFunction
  • Then using addEventListener , so that in the event click , execute toggle (function that does not exist)

Apparently one of the 2 is over, right?

One solution would be the following:

window.onload = function(){ 
    var icoMenu = document.getElementById('icon-menu');
  
    function toggle() {
        icoMenu.classList.toggle('changeMenu');
    }
    icoMenu.addEventListener('click', toggle, false);
}
.container-menu {
  background-color: #f00;
}
.container-menu.changeMenu {
  background-color: #ff0;
}
<div class="container-menu" id="icon-menu">
    <div class="bar-1">Bar 1</div>
    <div class="bar-2">Bar 2</div>
    <div class="bar-3">Bar 3</div>
</div>
    
answered by 29.11.2016 / 17:34
source