On my website, I have two menus located in different sections of the page. One menu is shown when the screen width is greater than 555px, while the other menu appears when the screen width is less than or equal to 555px. Although the menus are essentially the same, they serve different purposes on desktop and mobile devices.
The issue arises with the JavaScript functionality for dropdown options. It works perfectly for the first menu but fails to execute for the second menu. This is likely due to the fact that the JavaScript code still runs even when the parent div is set to display:none, causing it to malfunction on smaller screens.
In an attempt to address this problem, I decided to write code that dynamically creates and removes the div containing the menu based on browser width. Essentially, I wanted a JavaScript-controlled media query solution instead of simply using CSS to hide and show elements.
As someone new to JavaScript, I borrowed and modified existing code to achieve my goal. My main objective was to add the div when the browser width exceeds 555px and remove it when it goes below that threshold. With this approach, I hoped to streamline the process of adding/removing similar elements further down the page.
function DynamicDiv() {
var dynDiv = document.createElement("div");
dynDiv.id = "search-holder1";
dynDiv.innerHTML = "Created using JavaScript";
document.body.appendChild(dynDiv);
}
var elem = document.getElementById("search-holder1");
function myFunction(x) {
if (x.matches) { // If media query matches
DynamicDiv();
} else {
elem.parentNode.removeChild(elem);
}
}
var x = window.matchMedia("(max-width: 555px)")
myFunction(x) // Call listener function at run time
x.addListener(myFunction) // Attach listener function on state changes