0

I've made a responsive menu with a button. I've made a Javascript function which when I click on the button, the menu appears, but I want it to open when I click on the menu, and when I click on the icon again, it should close the menu.

Because now when I click the menu it stays opened.

Javascript

document.getElementById('menuIcon').addEventListener('click',function(){
     document.getElementById('rightMenu').style.display = 'block';
});
Jason Evans
  • 28,906
  • 14
  • 90
  • 154
Nasco.Chachev
  • 666
  • 6
  • 22

2 Answers2

2

To do this, you would need to toggle the element's visibility:

document.getElementById('menuIcon').addEventListener('click',function(){
        if(document.getElementById('rightMenu').style.display == 'none'){
            document.getElementById('rightMenu').style.display = 'block';
        }
        else{
            document.getElementById('rightMenu').style.display = 'none';
        }
    });
<button type="button" id="menuIcon">Menu Icon</button>
<br>
<textarea rows="2" cols="20" id="rightMenu">
This is the menu.
</textarea>
Blubberguy22
  • 1,344
  • 1
  • 17
  • 29
  • Yeah bro , that kinds works but I have a bug experience. That function works after the second click on the menu icon , any suggestions? – Nasco.Chachev Jan 15 '16 at 14:42
  • @Nasco.Chachev I added a code snippet so you can see how it works. Also I had a typo in my code, which I fixed (which probably caused the error). – Blubberguy22 Jan 15 '16 at 14:44
  • another problem appeared :D , It works but when I open in responsive mode , and then WITHOUT reloading page, I re-size the screen , my menu dissapears. – Nasco.Chachev Jan 15 '16 at 15:03
  • @Nasco.Chachev I think that's a separate problem that may require a separate question. – Blubberguy22 Jan 15 '16 at 15:08
1

//try this code.

var c=0;
document.getElementById('menuIcon').addEventListener('click',function(){
if(c == 0){
 document.getElementById('rightMenu').style.display = 'block';
 c = 1;
    }
else{
 document.getElementById('rightMenu').style.display = 'none';
 c = 0; 
    }
});