What is causing my Javascript media query for the sidebar to not function properly?

I am working on implementing a sidebar that slides out 250px using JavaScript on the desktop view. However, I want the sidebar to take up 100% width when viewed on mobile devices. Despite my attempts to use Media Queries in JavaScript to achieve this, I am encountering issues where the styles for the sidebar on the desktop view are being overwritten.

Here is the code structure:

 <nav class="navbar">
  <div id="toggle-btn" class="sidemenu-btn">
    <i class="fas fa-bars"></i>
  </div>
  <div id="toggle-nav" class="navbar-items animated fadeInLeft delay-1s">
    <a href="#home">Home</a>
    <a href="#about-me">About</a>
    <a href="#my-skills">Skills</a>
    <a href="#my-portfolio">Portfolio</a>
    <a href="#contact-me">Contact</a>
  </div>
</nav>

This is the CSS styling applied to the navbar:

 .navbar {
      height: 100%;
      width: 0;
      position: fixed;
      background: #141313;
    }

    /* Other CSS styles for the navbar */
    
@media screen and (max-width: 768px) {

.navbar {
  position: relative;
}


}

And here is the JavaScript code handling the toggle functionality based on screen size:

const toggleBtn = document.querySelector("#toggle-btn");
const toggleNav = document.querySelector(".navbar");

toggleBtn.addEventListener("click", sideMenu);
toggleBtn.addEventListener("click", mediaQuery);

function sideMenu() {
  // Functionality to toggle the sidebar width
}

function mediaQuery() {
  // Functionality for applying responsive design based on screen width
}

Answer №1

To change the width of the navbar-items, you can utilize media queries without the need for JavaScript. Here's an example:

@media (max-width: 768px) {
 .navbar-items {
   width: 100%;
 }
}

By simply adding a .open class to the .navbar element, you can trigger the transition effect. Here's how it can be implemented:

.navbar.open .navbar-items {
  width: 0;
}

This approach simplifies your JavaScript code as well. You can now achieve the desired functionality with minimal JS:

const toggleBtn = document.querySelector("#toggle-btn");
const toggleNav = document.querySelector(".navbar");

toggleBtn.addEventListener("click", sideMenu);

function sideMenu() {
  toggleNav.classList.toggle('open');
}

Answer №2

To customize the appearance of your website for mobile and desktop, it is best to use CSS for styling and JS for functionality. The code below addresses any style inconsistencies and improves the organization of your JavaScript.

CSS

.navbar{
   width: 250px;
   height: 100%;
   position: fixed;
   background: #141313;
 }     
 .navHidden{
  width: 0px !important;
 }
 /* adjusts for smaller screens */
 @media screen and (max-width:768px) {
   .navbar{
     width: 100%;
   }
 }

HTML

<nav class="navbar navHidden">

JS

function sideMenu() {
  toggleNav.classList.toggle("navHidden")
}

Sidenote

In the provided code snippet, on clicking the toggle button, the navbar's width is set to 250px, but then it is immediately changed to 100% in all cases, regardless of screen size. This prevents the toggle function from working properly.

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 steps do I need to take in order to develop a cross-platform icon using React Native

Currently in the process of creating a signup form, I am looking to incorporate icons that will display differently based on the platform being used. For example, when utilizing Ionicons, I would like the icon to appear as ios-person on iOS devices and m ...

Vue.js is limited in its ability to efficiently partition code into easily loadable modules

My current issue: I am facing a challenge with splitting my vue.js code into chunks. Despite trying multiple examples from tutorials, I am unable to successfully separate the components and load them only when necessary. Whenever I attempt to divide the c ...

The challenge with linking within Layerslider

Having some trouble with an external link to a specific layerslider slide (html version, NOT wordpress). Here is the webpage in question: After reaching out in the support forum, I was advised to use this javascript: <a href="javascript:void(0);" onc ...

Easy steps to include HTTP authentication headers in Spring Boot

I have been customizing my spring boot authorization server to fit my needs. Upon logging in with a username and password from my custom HTML page, I am aiming to redirect back to the /oauth/token endpoint to retrieve the access token. While this process ...

AJAX forms and snippets

I have successfully integrated comments into public activity following a tutorial on public activity #406 Public Activity. However, I am facing issues with submitting the comments via ajax. I have gone through several tutorials but haven't been able t ...

Using AJAX to assign PHP session variables

Is there a way to update the SESSION variable named "fullname" on Page 2 without causing the page to refresh? This is my attempt using AJAX: HTML code for Page 1: <input type="text" name="fullname" id="fullname" placeholder="Full name"> <butto ...

Is there a method to display a loading animation while the micro apps are being loaded in a single spa project?

Currently, I am working on a project using single spa and I need to implement a loader while my micro app is being loaded. Additionally, I also need the loader to be displayed when switching between these micro apps. Are there any methods to accomplish t ...

Customize the background color of FullCalendar in a React application

I'm currently using FullCalendar in my react app to showcase a calendar with events displayed. Right now, I have a day grid set up and I'm interested in changing the background color of the grid. The background color for today's date is alw ...

Check if the browser is compatible with the FREEZE and RESUME lifecycle events

Is there a method to determine if a browser is capable of registering the freeze and resume lifecycle events? Even after checking with Modernizr, a reliable JS library, it appears that these events are not supported. Although extremely beneficial, Safari ...

Unique hover tags such as those provided by Thinglink

Looking for a way to replicate the functionality of Thinglink? Imagine a dot on an image that, when hovered over, displays a text box - that's what I'm trying to achieve. I thought about using tooltips in Bootstrap, but I'm not sure if it ...

AngularJS - utilizing the directive $parsing to evaluate an expression and bind it to the scope object

I have set up my isolated directive to receive a string using the @ scope configuration. My goal is to convert this string into an object on the scope, so that I can manipulate its properties and values. Here's how it looks in HTML: <div directiv ...

Creating a hash map for an iteration through a jQuery collection

Using the jQuery .each function, I traverse through various div elements. By using console.log, the following output is obtained: 0.24 240, 0.1 100, 0.24 240, 0.24 240, The first number on each line represents a factor and the last number is the res ...

What are some strategies for getting neglected distribution files onto Bower despite being ignored by git?

I am in the process of creating a package for NPM and Bower. To maintain organization, I store my working files (ES6) in the src/ directory of the package and compile the distribution files (ES5, using Babel) in the lib/ directory. For version control, I ...

Is it possible to implement custom classes in @apply within a SCSS file in a Tailwind Next.js project?

Having trouble implementing a custom class overflow:inherit as @apply overflow-inherit in my next.js project with tailwind. It seems to be causing an error. Strangely, I can successfully use pre-built tailwind classes like @apply flex flex-col md:h-full h- ...

Sending back an HTTP response code from PHP to AJAX

I'm currently working on creating a login page for a website. The functionality involves using AJAX to send a request to a PHP script that verifies the username and password input. If the query returns a successful result, I use http_response_code(200 ...

Google Chrome users may experience unexpected position changes in jQueryUI modal dialog when dragging

Chrome version 26.0.1410.64 jQuery version 1.7.1 jQueryUI version latest The web app is created using asp.net webforms When the page is at the top, the dialog opens normally and functions correctly. However, if the page is scrolled down and the di ...

How to access additional legend labels in c3.js or billboard.js using JSON data?

I'm working with the following code snippet: ... normen is my json object .... $.each(normen, function(item) { chartX.push(this.feed_day) chartY.push(this.weight) }); createChart(char ...

Dynamic Bootstrap User Authentication Form

Currently, I am in the process of constructing a login form for my web application and have opted to use Bootstrap for its styling. To ensure that the screen is responsive, I've integrated the following "Meta Tag" into the structure: <meta name="v ...

Tips for managing onClick code when a user selects "open link in new tab" within a React js environment

How can I ensure that my tracking code runs when a user clicks a button in my React project, even if they open it in a new tab? Is there a solution for this in React JS? Here's a simple example: var Hello = React.createClass({ render: function( ...

What is the method for pulling information from MySQL and presenting it on a website using Node.js?

Currently, my goal is to retrieve data from MySQL and showcase it on my HTML page. The code snippet in server.js looks like this: const path = require('path'); const express = require('express'); const bodyParser = require("body-pa ...