Skip to content
Advertisement

JavaScript – Event listener with window.matchMedia not triggering

I’ve panned through countless solutions to this problem and none of them have fixed my issue. I very simply have a navigation bar, which, when on a mobile browser, disappears and becomes replaced with a button, whose function is to show and hide the navigation bar.

Now, I want my listener to, when the window is shrunk, show the button and hide the navigation bar. When the window is expanded, the button should be hidden and the navigation bar should be shown. The button is working as it should be, since the media query doesn’t affect it. My listener appears to not run at all, except when the page is reloaded.

My script is contained inside of a PHP header which is included at the beginning of all my pages. Here’s what I’ve got:

Media Query Listener (contained in header.php code)

// ... navbar code, opening script tag, yadda yadda
function mediaQueryCheck(inputQuery) {
    var content = document.getElementById("navigation");
    if (inputQuery.matches) {
        // it matches
        content.style.display = "none";
    } else {
        // it does not match
        content.style.display = "block";
    }
}
var mobileQuery = window.matchMedia("screen and (max-width: 638px)");
mediaQueryCheck(mobileQuery);
mobileQuery.addEventListener(mediaQueryCheck);
// closing script tag

The element #navigation is a div element containing the navigation bar. I will provide any other relevant code, if necessary.

Advertisement

Answer

Using addListener instead of addEventListener fixed the problem.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement