Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

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

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.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?