Window.matchMedia() calls multiple click events

Desi Source

I am very new to JavaScript. I am trying to create an overlay menu opened on click, that will be responsive depending on the screen size, 100% width for screen smaller than 768px and 50% for bigger ones. I managed to do so using window.matchMedia() but I am struggling with the final bit. Whenever I resize the window or open a new section a click event is called so the menu opens by itsels. I understand that I need to remove the multiple click events and set an event listener but I haven't been able to get it to work. Here is my code

var burger = document.getElementById('burger-click');


function openNav() {
    if (window.matchMedia("(max-width: 768px)").matches){
            document.getElementById("myNavPhone").style.width = "100%"; 
    } else {
            document.getElementById("myNavPhone").style.width = "50%";  } 

burger.addEventListener('click', openNav());

function closeNav() {
    document.getElementById("myNavPhone").style.width = "0%";

Any help would be greatly appreciated.



comments powered by Disqus