简体   繁体   中英

Prevent javascript from running when screen width is less or more than

I have 2 menus that are contained on the same page but in different locations. One appears when I have screen width > 555px and the parent div is set as display:none when under this size. The other is display:none when 555px or over and shows when less than 555px. Its the same menu but one is on a different section of the page for mobile/smaller screens.

I have javascript on some of the drop down options on the menu and it works for the first menu but not the second, I believe because the js is still attempting to run for the display:none so on the second attempt (on the small screens) it doesn't work.

I'm probably over-complicating what needs to be done but I've attempted to create some code that uses js to create the div that contains the menu code for desktop and mobile and removes them when it shouldn't... so a media query version controlled by js rather than css that rather than hide the div and content will actually make it not be present.

I'm a complete novice at javascript and have just attempted to adapt other code I've seen, basically all I want to do is when >555px browser width add and when it moves under remove then I can use the same code down the page to add/remove div id="y"...

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

Here is my way:

function chooseMenu() {
    var width = window.innerWidth;
    if (width > 555) {
        //Add your div
    else {
        //If div is in document then remove, and add mobile div
    }
}
window.onresize = chooseMenu;

You should probably do the same function at the beggining with an anonymous function too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM