Adapting Classes in Javascript Based on Screen Width: A Step-by-Step Guide

I'm dealing with two separate menus - one for mobile version and one for PC version. However, the mobile menu seems to be overlapping/blocking the PC menu. How can I resolve this issue?

I've attempted various solutions such as removing the mobile menu in media queries when changing screen width, but it hasn't been successful. I also tried using Javascript to add/remove classes, but it only affected the mobile menu and not the PC menu.

window.onload = function() {
 overlay();
};

function overlay() {
  let nav = document.getElementById("nav");
  if (document.body.style.width < "991px") {
    nav.classList.add("overlay");
  } else {
    nav.classList.remove("overlay");
  }
};

My goal is to have both menus work without any conflicts, but currently, the PC menu is not functioning properly while the mobile menu works fine. There are no error messages in the console.

Answer №1

document.body.style.width will only work if you explicitly set the body size. To ensure it works regardless of body size, consider using screen.width (or window.innerWidth for a resizing window) for comparison.

Here's an example for easy use:


window.onload = function() {
 overlay();
};

function overlay() {
 let nav = document.getElementById("nav");
 if (window.innerWidth < 991) {
   nav.classList.add("overlay");
 } else {
   nav.classList.remove("overlay");
 }
};

Useful Links

Answer №2

Here is the solution. Much appreciation to everyone for their help!

onload = function() {
  toggleMenus();
}

window.onresize = function() {
  toggleMenus();
}

function toggleMenus() {
  var width = window.innerWidth;
  console.log(width);
  
  if(width < 767) { //mobile
    $(".mobile-menu").show();
    $(".desktop-menu").hide();
  }
  else { //desktop
    $(".mobile-menu").hide();
    $(".desktop-menu").show();
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="mobile-menu">
  Some mobile menu content
</div>

<div class="desktop-menu">
  Some desktop menu content
</div>

Answer №3

function bar() {
   console.log(window.innerWidth, window.innerHeight)
}

window.addEventListener('resize', bar)

You can now replace the incorrect class with the correct one

Answer №4

There are a variety of methods to achieve this:

1- Utilizing CSS media queries:

/*Mobile*/
@media(max-width: 767px) {
  .mobile-menu {
    display: block;
  }
  .desktop-menu {
    display: none;
  }
}

/*Desktop*/
@media(min-width: 767px) {
  .mobile-menu {
    display: none;
  }
  .desktop-menu {
    display: block;
  }
}
<div class="mobile-menu">
  Some mobile menu content
</div>

<div class="desktop-menu">
  Some desktop menu content
</div>

2- Implementing Javascript:

In javascript, you can utilize window.innerWidth to access the window's width, and then show/hide divs accordingly. Remember to update changes on window resize events as well:

onload = function() {
  toggleMenus();
}

window.onresize = function() {
  toggleMenus();
}

function toggleMenus() {
  var width = window.innerWidth;
  console.log(width);
  
  if(width < 767) { //mobile
    $(".mobile-menu").show();
    $(".desktop-menu").hide();
  }
  else { //desktop
    $(".mobile-menu").hide();
    $(".desktop-menu").show();
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="mobile-menu">
  Some mobile menu content
</div>

<div class="desktop-menu">
  Some desktop menu content
</div>

3- Leveraging Bootstrap 4:

If you prefer not to develop custom logic, Bootstrap 4 classes offer options to show/hide divs based on screen size. For your requirements, consider using:

d-block with d-md-none to hide a div on desktop and show it on mobile

d-sm-none with d-xs-none and d-md-block to hide a div on mobile and show it on desktop.

<div class="mobile-menu d-md-none">
  Some mobile menu content
</div>

<div class="desktop-menu d-sm-none d-xs-none d-md-block">
  Some desktop menu content
</div>

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

What could be the reason for the lack of response from the jquery element on an

Recently, I've been working on a jQuery project with sticky headers. However, when I tested it on my iPad, I noticed a slight delay and the header jumping around the page. I'm wondering if this issue can be resolved within the code itself or if ...

Discrepancy in Angular Material Buttons with theme design

I recently installed Angular 10 along with Angular Materials using the command ng add @angular/material I opted for the custom theme: Purple/Green The next step was to add a Toolbar by simply copying and pasting code from Google's site. However, I a ...

Unable to apply inset box-shadow to image

I've added a box-shadow to my image. box-shadow: 0 0 10px RED inset However, the shadow is not showing up on the image. When I use Firebug to change the image path, I can see that the shadow is behind the image. How can I apply the shadow directly ...

Encountering a npm script error while running on a Windows operating

While using webpack to build my application, I encountered the following error message in the command prompt: [email protected] dev D:\Myprograms\java script\forkify webpack --mode development The error mentioned: Insufficient num ...

"Exploring the dynamic duo of Angular2 and ng2Material

I am currently facing an issue with the styling in my code while using ng2Material with Angular2. First: A demonstration of Material style functioning properly can be seen in this plunker. When you click on the button, you will notice an animation effect. ...

Ways to create gaps among the links in the Bootstrap 4 navigation bar?

I recently put together a Bootstrap 4 navbar and now I'm looking to increase the spacing between the items on the right side of the navbar. <nav id="menu" class="navbar navbar-expand-md sticky-top"> <div class="site-branding navbar-brand c ...

Using Vue.js to group JSON arrays multiple times

I have a program that I utilize to import a CSV data file and then convert it into JSON format. The resulting JSON structure is as follows: { "Class": "Cultivated Mushrooms", "Type": "Shii-take", "Grade": "Medium", "LvH": "SP", "Description": " ...

Obtaining an identification using JQuery for content that is constantly changing

I am currently developing dynamic content tabs using PHP, with one of the objects being a datatable within the tab. In order to define the ID via PHP, I use the following code: PHP: echo '<table class="table table-striped table-bordered table-hov ...

Problems with WordPress Theme Rendering in Outdated Versions of Internet Explorer

Currently, I am developing a website for Chase on the Lake at http://chaseonthelake.com/. While everything looks perfect in FireFox, there are some display issues when viewing it in Internet Explorer. The dropdown transparency is not showing correctly, m ...

Display the number of likes without having to refresh the page

On my website, there is a like/unlike post feature. When I click the like button, I want the value of check2 to appear next to the like button without needing to refresh the page. Currently, after clicking like, the data is inserted but only appears after ...

The error message "Cannot access property 'findAll' of undefined in expressjs" is displayed

An issue has occurred with ExpressJS: TypeError - Cannot read property 'findAll' of undefined. It seems that all Sequelize functions are not working correctly. Numerous errors are popping up, such as "Cannot read property 'sequelize method& ...

Having difficulty passing the new state value using props in ReactJS

I am facing an issue with sending state values from parent to child components. Initially, the state value is empty but after making an API call, the state value gets updated. However, the props in my child component are still stuck with the initial empty ...

Chosen option within the AntD Select component

Using the AntD select component, there seems to be an issue where it displays "id" instead of "name" when selecting options. Is there a solution available for this problem? const MyComponent = () => { const data = [ { id: "5c83c2d ...

Utilizing grease/tampermonkey (or any other browser extension) to filter out specific characters within webpage elements

Forgive me if my language is not accurate, as I am still learning about programming. The forum that I visit has cluttered the page with unnecessary and glitchy images and text for a promotion. This has made the forum difficult to navigate. I was successful ...

The sorting process fails to make any changes, thus leaving the state unaffected

Is there a way to sort an array of objects in descending order by their id? No errors appear in the console. Even after calling the sort method, the state of allPosts remains unchanged. import { useState } from "react"; import Button f ...

Arrange an asynchronous function in Node.js

I have been attempting to set up a schedule for an asynchronous function (with async/await return type) to run every two minutes. Although I have tried using the generic setInterval, as well as various node modules such as node-schedule, cron, node-cron, ...

The directive binding value is accurate, however it is failing to return a true result

The behavior of a custom directive is puzzling me. When I directly pass in a value, it works fine. However, if I bind the value to a variable, it doesn't work as expected. Interestingly, when I use console.log to show the value, it appears to be corre ...

The sticky element should only be active when the visible section is overflowing vertically. There should be no scrollbar if the height is minimal

I'm currently working on a Whatsapp-style navigation bar and facing an issue with the sticky navbar functionality. https://i.stack.imgur.com/Cy3lA.gif Please refer to the details below for more information. To resolve this issue, I have included ...

Deactivating the Grid and its offspring in React.js MUI

Is it possible to Disable the Grid (MUI Component) and its Children in React js? Additionally, how can we Disable any Container and its items in React js, regardless of the type of children they have? For example: <Grid item disabled // ...

Attempting to resolve the Bootstrap issue, currently in search of a suitable solution

Today I made the decision to utilize bootstrap to create a menu, but unfortunately, I've encountered a strange bug or conflict involving jQuery, potentially the UI, and Bootstrap. If you'd like, you can take a look at the picture provided in the ...