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
879pxand 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
match property (the value of which would be
false based on the condition met) returned by the
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.