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

Exploring the object tag box model and its properties for width and padding in Firefox version 6

Hey there, I've been puzzled by the fact that my Firefox browser seems to be using a different box model for my video embeds compared to Chrome. Even though the same CSS rules are being applied, if the object tag includes attributes like data="whateve ...

Ways to enhance the functionality of an input component

Within my React app, I have an input component that triggers an onChange event when connected to another component: <input type="text" onChange={onChange} /> Now, I am looking to enhance this input component by incorporating a prop from another com ...

Employing asynchronous operations and the power of async/await for achieving seamless integration

I am currently facing an issue where I need to retrieve queries from a database stored in Postgres. A function is utilized, which employs a callback mechanism. In order to fetch rows from the database, there exists a function called getRecipesByCategoryFo ...

The issue arises when using IE8/9 with $.get and .html() functions, as the retrieved data

Below is a snippet of JavaScript code that I am currently working with: $(".refresh").on("click touch", function () { $.get($("a.suggest-date").attr('href') + '#suggestedDate', null, function (result) { console.log(result); ...

Is getElementById() returning null?

I'm currently working on a JavaScript program that takes an image URL and displays it on the page by creating an <img> tag. This way, I can easily add multiple images to the page. Here is my code: <!DOCTYPE html> <html lang="en&quo ...

Empty space under the banner in Wordpress theme Avada

I can't seem to locate the CSS class for a blank space that appears below the header on one of my pages. This space is situated between the header and "SERVICIOS 24 HORAS". Any ideas on how I can remove this mysterious gap? My website is built wit ...

Utilize CSS to display line breaks within a browser output

If I wrap text in a <pre> element, line breaks will be displayed in the browser without needing to use <br/> tags. Can this same effect be achieved by utilizing CSS with a <div> element? ...

Error Message: Expecting an Object - Microsoft JScript Runtime Error in Node.js

I am starting my journey with Node JS and I encountered an unexpected error while running my code. Microsoft Jscript Runtime Error appeared, stating that "Object expected at line number 1". const fs = require('fs'); function FileObject () { thi ...

Concealing and revealing the triangular indicator within a bullet diagram using the AngularJS-nvd3-directives library

I am currently utilizing the nvd3-bullet-chart feature from the angularjs-nvd3-directives library in order to present maximum, current, and average data. To exclude the minimum variable from the array for display purposes, I have set its value to 0. In a ...

Clearing hoverIntent using jQuery

In my scenario, I have three items identified as X, Y, and Z. The functionality of hovering is controlled by the hoverIntent. When I hover on item X, a tooltip is displayed using the following code: jQuery('.tooltiper').hoverIntent({ ove ...

Populate Vue components dynamically without the need for additional frameworks like Nuxt in Vue3

My goal is to develop a checksheet application using Vue, where the tasks are specified in an excel file. ===== To start, task A needs to be completed. Followed by task B. and so on... ===== I am considering creating a CheckItem.vue component fo ...

Updating a value using jQuery AJAX techniques

Using jQuery AJAX, I am loading the content of a page in this way: $(document).ready(function(){ $('#next').click(function(event){ $.ajax({ url: "load.php?start="+$('#lastid').text(), success: function(html){ $("#results"). ...

Hide the menu when a menu link is selected

After conducting extensive research, I have come across several scripts that can achieve what I am trying to do. However, I am unsure of how to implement them with my particular WordPress theme. Therefore, I am seeking assistance here: The theme I am usin ...

Challenges regarding variable scope in JavaScript

Presented below is the JavaScript code I am currently using, which involves jQuery: function language(language) { var text = new Object(); $.ajax({ type: "GET", url: "includes/xml/languages/" + language + ".xml", dataType: ...

Looking for a foolproof method to determine if a string contains any of the elements in a given array of substrings? And if found, how

I am currently faced with the task of decoding multiple URLs, specifically focusing on encoded special characters like "+", "|", and more. My approach involves having a collection of encoded characters that I need to locate in the URL string. What is the ...

Retrieving the current value of the selected option using JQuery

I am working on a feature where I have different quantities in selects after each button click. <button type="button" class="btn btn-sm btn-primary" id="addtocart2" >Button1</button> <select id="quantity1" class="ml- ...

Sending parameters with $location.path() in AngularJS

Having trouble creating a redirection call in the controller with a numerical parameter. Here is the code I've been using: $location.path('/tasklist/:$rootScope.job_id'); I have also attempted the following: $location.path("/tasklist/",$r ...

What is the best way to ensure my responsive form is centered and aligned properly with all other elements on the page

Link to website This final step is all that stands between me and the completion of my website deployment. However, I am faced with a persistent issue that has me stumped. It seems that there is an unexplained margin on the left side of the contact form, ...

"Vanishing act: The mysterious disappearance of an empty JSON

After defining a JSON object and posting it to the backend (Node.js), there appears to be an issue. var imj = {}; imj.images = []; $.post("/image/uploadImages", imj, function(feedback){ ..... Unfortunately, when the backend received the data, the "images ...

Issue with JQuery event handlers becoming unresponsive upon resizing the window

JSBin link: http://jsbin.com/4QLDC/6 Here is the JS code snippet that I have written: var toggleContent = function (event) { $(event.target).siblings().toggle(); }; var showOrHidePanels = function () { var windowHeight = $(window).height(); v ...