Toggling state of the checkbox based on the viewport width in JavaScript

Amit Merchant · September 18, 2022 ·

Recently, I stumbled upon a problem where I had to toggle the state of the checkbox based on the viewport width. So, let’s say, if the viewport width is changed and is less than 879px and the checkbox is checked, then it should be unchecked.

That’s because I was using the checkbox to toggle the visibility of the hamburger menu and the menu was visible only if the viewport’s width was less than 879px. So, if the user changes the viewport’s width and if it was greater than 879px and the checkbox was checked, then the menu was visible and that’s not what I wanted.

To fix this, here’s what I did.

window.matchMedia('screen and (min-width: 879px)')
    .addEventListener('change', ({ matches }) => {
        if (matches && document.querySelector('.menu-btn').checked) {
            document.querySelector('.menu-btn').checked = false
        }
});

Let’s break down the above code.

First, I’m using the window.matchMedia() method to check if the viewport width is greater than 879px. If it is, then I’m using the addEventListener() method to listen for the change event on the MediaQueryList object’s match property (the value of which would be true or false based on the condition met) returned by the window.matchMedia() method.

Then, I’m checking if the viewport width is greater than 879px and the checkbox is checked. If it is, then I’m unchecking the checkbox.

And that’s how I was able to hide the hamburger menu when the viewport width is greater than 879px and the checkbox is checked.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!

Comments?