Stop the execution of javascript code based on the screen width

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

Answer №1

This is how I like to handle it:

function displayMenu() {
    var screenSize = window.innerWidth;
    if (screenSize > 555) {
        //Insert your div for desktop view
    else {
        //If div already exists, remove and insert mobile view div
    }
}
window.onresize = displayMenu;

You may also want to consider using an anonymous function at the beginning as well.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying hidden Divs in React Typescript that are currently not visible

I have an array with various titles ranging from Title1 to Title8. When these titles are not empty, I am able to display their corresponding information successfully. Now, my goal is to include a button that will allow me to show all fields. For example, ...

Which callback function is best suited for handling the response in an XMLHttpRequest and rendering it on the webpage?

Upon a user action on the page, an AJAX request is made to my Node.js Express server to send data. Here's what happens next: router.post('/', function(req, res){ //user authentication first, then inside that callback res.redirect('/d ...

Sending data from configuration to factory in AngularJS and UI Router

Trying to perform a search in an http call with a dynamic value based on the current view. The factory setup is as follows: .factory('SearchService', ['$http','$filter', function($http, $filter) { var service = { get ...

I've been attempting to develop a React application, but I consistently encounter the following error: "npm ERR! cb() function was never invoked!"

Here is the issue at hand: HP@DESKTOP-1HP83V8 MINGW64 ~/Desktop/Web-Development (master) $ npx create-react-app my-app A new React app is being created in C:\Users\HP\Desktop\Web-Development\my-app. Packages are being installed. ...

What is the best way to compare two arrays of objects and then append a new key to the objects in the second array?

Consider the following arrays where you are tasked with comparing them and returning a filtered version of array two containing elements found in array one: const array1 = [ { name: "Jack", age: 54, title: "IT Engineer" }, { na ...

A step-by-step guide to incorporating VeeValidate with vue-i18n

When a click event is triggered, I am able to change the language in vue-i18n. However, I am facing an issue with changing the vee-validate dictionary to match the same language. Main.js import VeeValidate from 'vee-validate' import validations ...

What size should I use for creating a responsive website?

After scouring the internet, I stumbled upon numerous dimensions referred to as proper for developing responsive designs. However, I am specifically interested in identifying the ideal breakpoints, particularly for mobile devices with small screens like ...

How to implement setState within a Promise function using useEffect in React functional components with hooks?

I am struggling to set the value of a hook within a Promise function inside a useEffect(), and then store the returned promise value in the fruit hook so that it can be accessed in the return function of MyComponent() This is what I have attempted so far: ...

Check for support of Symbol.toStringTag in JavaScript

Can this function reliably detect the presence of @@toStringTag in all environments? function hasToStringTagSymbol() { if (Symbol && (typeof Symbol() == "symbol") && !!Symbol.toStringTag) { var xTest = function () { }; xTest.prototyp ...

Utilize the conditional GET method when including scripts through tags in an HTML webpage

Is it possible to benefit from HTTP conditional requests when including a script in the head section of a page? My goal is to cache dynamically downloaded JavaScript files that are added to the head section using script tags. If this approach isn't fe ...

Adjust padding of radio button labels in Qualtrics for a cleaner, more streamlined appearance

As I delve into the world of CSS, my goal is to customize the existing survey theme known as "Minimal 2014". Specifically, my focus is on minimizing the spacing in various areas to create a more compact design. So far, I've successfully reduced the g ...

Showing post response (XMLHttpRequest) on Chrome extension interface instead of Python console

I am currently developing a Chrome extension that sends a post request with information about the specific URL being browsed by the user to Flask (local host). A web scraping process is then carried out on this URL to determine a category based on the obta ...

Tips for personalizing the FileField in wtforms to function as an image button

I'm attempting to display an image from my project's directory as an icon instead of the standard "choose file" button. Unfortunately, my attempts thus far have been unsuccessful. Not only is the image not loading, but the original button is only ...

Tips for creating a Google Chart using temperature and humidity data sourced from an XML file

Below is the XML file I am working with: <data> <temp>21</temp> <humidity>17</humidity> <analog>670</analog> <analog>908</analog> <analog>628</analog> <analog>909</analog> <L ...

The search text box is mysteriously absent from each column in the datatables

I am utilizing jQuery Datatables to construct a table with data retrieved from MySQL. This is how my table appears: LOT_LOCATION, Zone Attribute, LOTID, Design_ID, Board_ID1, QA_WORK_REQUEST_NO, QA_CONTACT_NAME, QA_PROCESS_NAME, CURRENT_QTY, Date, Temp ...

Having trouble updating the URL path with the $location service in Angular

I'm facing a challenge in updating the URL path using the $location.url service, as it's not reflecting the changes correctly. For instance, my current URL path is http://localhost:64621/module/commercial/#/company/98163780-4fa6-426f-8753-e05a6 ...

Angular JS effectively prevents redundant data from being displayed to users when scrolling infinitely while also efficiently removing DOM elements for previous data

I'm currently working on implementing AngularJS Infinite Scroll without using jQuery. My goal is to display the first 3 data items when the page loads and then load the next 3 data items from a JSON array object as the user scrolls. The issue I am fac ...

In the realm of JavaScript, what happens when a function yields yet another function while also welcoming another function as an argument?

After following a Node & Express project tutorial on YouTube, I encountered the following code snippet in an async JavaScript file: const asyncHWrapper = (fn) => { return async (req, res, next) => { try { await fn(req, res, next); } c ...

Struggling to apply the active class using a combination of jquery, nodejs, express, and bootstrap

I've been working on an express generator Node.js application that uses Bootstrap and Jade. I'm facing issues with setting the active state of the navigation bar. After trying to implement some jQuery, I noticed that when I click on the nav bar, ...

Ways to acquire dynamic content without relying on Remark/Grey Matter

In my stack of technologies, I am using nextJS with react and typescript. While I have successfully set dynamic routes for my blog posts, I am now facing a challenge in creating pages that do not rely on markdown. Despite searching extensively for code exa ...