What is the best way to adjust the width of a navbar using JavaScript?

I am experimenting with a responsive design and facing an issue - the width of my #menu in CSS is initially set to 0, but I need to change this value based on user input using JavaScript.

Now, I want to dynamically adjust the width of the menu for different screen sizes by modifying the CSS. Here is what I have tried:

@media only screen and (min-width: 320px) and (max-width: 480px) {
#menu {
   height: 30px;
   width: 200px;
  }
}

However, this approach does not work as the width is set through JavaScript.

How can I update the JavaScript code to achieve this?

function toggleMenu() {
  var menu = document.getElementById("menu");
  var basket = document.getElementById("basket1");
    if (menu.style.width == '420px') {
    menu.style.width = '0';
    menu.style.opacity = 1;
    basket.style.opacity = 1;
  } else {
    menu.style.width = "420px";
    menu.style.opacity = 1;
    basket.style.opacity = 0;
    }
}
.nav-menu {
  overflow: hidden;
    height: 35px;
    position: absolute;
    right: 49px;
    top: 10px;
    background: rgba(14, 13, 13, 0.7);
    transition: 0.3s ease-in-out;
    box-shadow: 0 0 5px rgba(14, 13, 13, 0.7);
}
#menu { 
    width: 0;
}
<div>
 <div id="menuToggle">
    <input type="checkbox" onclick="toggleMenu()">
    <span id="span1"></span>
    <span id="span2"></span>
    <span id="span3"></span>
  </div>
  <div>
     <nav class="nav-menu" id="menu">
       <ul>
         <li><a href="#" onclick="openSection('figurative1')">FIGURATIVE</a></li>
         <li><a href="#" onclick="openSection('painting1')">PAINTING</a></li>
         <li><a href="#" onclick="openSection('portrait1')">PORTRAIT</a></li>
         <li><a href="#" onclick="openSection('stilllife1')">STILL LIFE</a></li>
         <li><a href="#" onclick="openSection('landscape1')">LANDSCAPE</a></li>
       </ul>
     </nav>
  </div>
</div>

https://codepen.io/tatarusetskaya/pen/XWpzNZa

Answer №1

When creating a responsive navbar or any other element, it is advisable not to fix the width of the element. Instead, you can utilize the max-width property. This will dynamically adjust the width of your navbar as the screen size decreases to the specified maximum width. Additionally, you have the option to modify the width of any element by using media queries.

Answer №2

If you want to override styles in CSS, consider using the !important declaration.

For example:

@media only screen and (min-width: 320px) and (max-width: 480px) {
#menu {
   height: 30px;
   width: 200px !important;
  }
}

Answer №3

The width of your element is consistently set to 0 due to the inline styling applied by your JavaScript code, which takes precedence over other style rules. For a responsive navigation design, it is recommended not to specify fixed widths for containers but rather let the content dictate the width. Utilizing media queries would be a more appropriate approach in this scenario. Additionally,

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

Challenges with implementing @Html.EditorForModel

Currently, I am developing a web application using asp.net's mvc-5 framework. In this project, I have implemented the following model class: public class Details4 { [HiddenInput(DisplayValue=false)] public string RESOURCENAME { se ...

Make an element in jQuery draggable but always within the viewport

My issue is that when I resize the window, the element stays in its position until I start dragging it. Once I drag it and then resize the window again, it doesn't stay within its container. To better illustrate my problem, you can view a demo on Fid ...

Utilize the v-for second argument in VueJS 2 to showcase the index and index+1

For a VueJS 2 project, I am tasked with enhancing the display of the first and second elements in an array by making them stand out from the rest. To achieve this, I am utilizing the v-for syntax to iterate over a child component within a parent component. ...

What is the best way to execute two asynchronous operations simultaneously in Node.js, treating them as a single atomic operation?

In my current setup, I have a function that calls two asynchronous functions. This main function is responsible for handling user requests. Let me show you an example: mainFunction(req, res, done) { asyncExist(req, function(exists) { if (!exists ...

Occasional issue with Bootstrap where jQuery is required for JavaScript

Recently I have started implementing requirejs in my project, but I have encountered a persistent issue that I am unable to resolve. The error message "Bootstrap's JavaScript requires jQuery" randomly appears when I load my application. Below are the ...

Ways to correct inverted text in live syntax highlighting using javascript

My coding script has a highlighting feature for keywords, but unfortunately, it is causing some unwanted effects like reversing and mixing up the text. I am seeking assistance to fix this issue, whether it be by un-reversing the text, moving the cursor to ...

A guide to filling an irregular shape (such as a star) based on a percentage using CSS in a React project

I am currently working on developing a React component that showcases a rating percentage using a star icon with two different shades. For example, if the input rating is 79%, I want to display a star with 79% of it in gold color and the remaining 21% in ...

Is it necessary for vertex labels to be distinct within a graph?

I am currently developing a browser-based application that allows users to create graphs, manipulate them, and run algorithms on them. At the moment, each vertex is represented by a unique positive integer. However, I am considering implementing labeled ve ...

Determine which points fall within a specified radius by utilizing solely an array

I'm developing an application that utilizes Leaflet to store GPS coordinates of specific locations in a table format [lat,lng]. This functionality is only accessible from the back end. On the front end, I need to retrieve the current position and gen ...

Is there a method to incorporate scss into a project without requiring a separate stylesheet?

I am currently working on a Gatsby application that utilizes SCSS. My code snippet looks like this: import React from "react"; import styles from "./mosaic.module.scss"; import Tile from '../tile/tile'; const Mosaic = (): JSX.Element => ( ...

When I hover over the navigation bar, a submenu pops up. However, as I try to navigate to the submenu, I often end up accidentally selecting a different item on the navigation bar

I'm trying to find an answer but can't seem to remember where I saw it. Here's the situation: a horizontal nav bar with a dark blue selection and a red sub-menu. When the user hovers over a black arrow, it crosses into a light-blue nav item ...

Sending a object as an argument to a function

Could someone please help me understand the purpose of passing an object as a function parameter? I have been trying to learn Next.js and they frequently use this method in their code. If anyone could provide a brief explanation of why this is done, it wo ...

Expansion issue with Bootstrap panel

I am currently using Bootstrap 3 for the development of a social networking site. The issue I'm encountering involves displaying comments within a panel footer on toggle. However, the comments are extending beyond the footer area. Can anyone provide g ...

jquery mobile popup message will fade away within a short time interval

In my main page, I have the following code: $(document).bind("pageinit", function () { $.mobile.loading('hide'); }); I am displaying a popup message using the following code: $.mobile.loading('show&apos ...

Making an Angular 6 HTTP GET call using HTTP-Basic authentication

When attempting to access a URL that requires Basic Authentication, and returns JSON data, what is the proper way to include my username and password in the following HTTP request? private postsURL = "https://jsonExample/posts"; getPosts(): Observable& ...

Curvature Factor equals Overflow of Color

After trying various solutions like "background-clip: padding-box;" to address the issue of background color bleeding outside of the border, I'm still not completely satisfied with the result. Is there a more effective fix for this problem? Check out ...

Using a vanilla JS object as a prop for a child component

I have created a custom Message class in my application to handle incoming messages, which is defined in message.js. Within message.js, I've implemented two classes: Message and EventEmit. The render function in my Message class requires passing an E ...

Are you in search of an opening <html> tag for your project?

When I use Initializer to quickly generate HTML5 + Boostrap boilerplates, I noticed that the HTML document it creates does not include an opening <html> tag. This got me curious. Here is the beginning portion of the code generated by Initializr: &l ...

Can TypeScript modules be designed to function in this way?

Seeking to create a versatile function / module / class that can be called in various ways: const myvar = MyModule('a parameter').methodA().methodB().methodC(); //and also this option should work const myvar = MyModule('a parameter') ...

The Arrival of Link: A Countdown Timer

I'm attempting to create a countdown timer that reveals a link after 20 minutes. Currently, this is my progress... <script type="text/javascript"> window.onload = function() { countDown('my_div1', '<a href="cdtl.html" ...