I am building a web app that has a fixed positioned Sidenav bar on Desktop always visible but on Mobile the Sidenav is hidden and the user clicks the Hamburguer button to Show it as modal and of course Close it later (Using Javascript for that).
The Problem
Lets imagine an iPad, that Vertically display mobile view but Horizontally displays the desktop view. If the user is Vertically and he toggles the Sidenav Visible and then Hidden, but if later he changes the orientation to Horizontal the Sidenav will be hidden, and the expected behaviour is that on desktop the Sidenav is always visible (I think this is because CSS Styles are loaded on page render, and when I change the styles with JS to toggle visibility it remains that way even when the DOM resized).
Question
The solution that occurred to me is having 2 identical Sidenavs and 1 show only on desktop and 1 only on mobile, and that way the styles of 1 dont affect the other, but that means a duplicated code.
If I want a more elegant solution without duplicating a whole block of code, I wonder if there is a way to reset all CSS values when it detects a Media Query Breakpoint, or what could be another solution?
I hope I explained well, and thank you for you help.
Edit: Solution I found thanks tacoshy's comment
When the Resize Event detects the Breakpoint it forces to trigger the Hide/Show function for the Sidenav
const showDrawer = () => {
var drawer = document.querySelector('.drawer');
var drawerBack = document.querySelector('.drawer-back');
drawerBack.style.opacity = "1";
drawer.style.left = "0";
drawerBack.style.visibility = "visible"
}
const hideDrawer = () => {
var drawer = document.querySelector('.drawer');
var drawerBack = document.querySelector('.drawer-back');
drawerBack.style.opacity = "0";
drawer.style.left = "-16rem";
setTimeout(
() => {drawerBack.style.visibility = "hidden"}
, 500);
}
window.addEventListener("resize", resizeFunction);
const resizeFunction = () => {
var w = window.outerWidth;
var drawer = document.querySelector('.drawer');
var drawerBack = document.querySelector('.drawer-back');
if (w > 1216) {
drawerBack.style.opacity = "1";
drawer.style.left = "0";
drawerBack.style.visibility = "visible";
} else {
drawerBack.style.opacity = "0";
drawer.style.left = "-16rem";
setTimeout(
() => {drawerBack.style.visibility = "hidden"}
, 500);
}
}