What is causing my mobile navbar to not collapse when the page loads?

I'm having trouble collapsing the navbar on mobile devices. Currently, the navbar only collapses when I manually resize the tab. It seems like the issue is related to it not checking the screen size when the site initially loads. I've attempted to use addeventlisteners but keep encountering errors due to unexpected tokens. The original code I had was:

function openNav() {
  document.getElementById("mySidebar").style.width = "190px";
  document.getElementById("main").style.marginLeft = "190px";
}

function closeNav() {
  document.getElementById("mySidebar").style.width = "0";
  document.getElementById("main").style.marginLeft= "0";
}





var x = window.matchMedia("(max-width: 600px)")
myFunction(x) // Call listener function at run time
x.addListener(myFunction) // Attach listener function on state changes


function myFunction(x) {
  if (x.matches) { // If media query matches
      
      closeNav()
    
  }
    
  
}

After seeking help from others, I decided to experiment with this:

var x = window.matchMedia("(max-width: 600px)")
x.addEventListener("change", () => {
    myFunction(x);
});

and

window.addEventListener('resize', ()=>{
 var x = window.matchMedia("(max-width: 600px)")
 if (x.matches) { // If media query matches 
  closeNav() 
 }
 });

I've been up for hours trying to solve this, and I know it's probably something simple that I'm missing.

Answer №1

Instead of relying solely on JavaScript, consider utilizing CSS @media queries in the following ways:

@media only screen and (min-width: 0px) and (max-width: 767px) { 'Insert your style adjustments here' }

@media only screen and (min-width: 768px) and (max-width: 1024px) and (orientation: portrait) { 'Specific styles for tablet portrait view' }

@media only screen and (min-width: 768px) and (max-width: 1024px) and (orientation: landscape) { 'Tablet landscape view customization' }

Additionally, do not overlook adding a viewport meta tag to the head section of your webpage.

meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=3"

(Ensure the above meta tag is enclosed in < />)

The viewport meta tag allows your website to respond to browser resizing, enabling you to create adaptable web layouts and control element visibility based on specific device sizes.

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

Adaptive video player for complete YouTube experience

Is there a way to incorporate a YouTube video as the background of a div, similar to how it is done on this site, using a <video> tag and ensuring that the video "covers" the entire div without any empty spaces while maintaining its original ratio? ...

Determine whether a JavaScript string exclusively consists of punctuation marks

In an if statement, I want to verify whether the given string contains any punctuation. If it does contain punctuation marks, I intend to display a pop-up alert message. if((/*regex presumably*/.test(rspace))==true||(/*regex presumably*/.test(sspace))==tr ...

Transform JavaScript object into desired structure

let obj = { "rec": [{ "id": "25837", "contentId": "25838" }, { "id": "25839", "contentId": "25838" }, { "id": "25838" }, { "id": "25 ...

Tips for setting up Greasemonkey to automatically click on an unusual link on a particular website

I'm not a master coder by any means; I can handle some scripts but that's about it. Treat me like a total beginner, please! ;-) I want to automatically expand two specific links on a webpage using a GM Script. On a French dating site in the prof ...

Send a parameter to a React hook

I am facing an issue with a Component that is using a separate hook. I am unable to pass any value to that hook, which is necessary for my use case. const onEdit = (index: number) => useMediaLinkImage(img => { setNodeImages(imgData => { ...

Tips for integrating external JavaScript libraries and stylesheets into a widget

I am currently working on developing a custom Javascript widget that requires users to insert specific lines of code into their web pages. This code will then dynamically add an externally hosted javascript file, allowing me to inject HTML content onto the ...

The NVDA screen reader is unable to detect visually hidden text

In the code snippet below, part of a table is shown where some text is meant to be displayed visibly and some should be visually hidden. However, it seems that the screen reader does not detect the visually hidden text when hovering over it with a mouse. T ...

Learn the process of assigning the present date using the jQuery UI date picker tool

I am looking to implement the feature of setting the current date using Angular/Jquery UI date picker. I have created a directive specifically for this purpose which is shown below: app.directive('basicpicker', function() { return { rest ...

AngularJS $routeProvider is experiencing difficulties with its routing functionality

I am a beginner with Angular and I'm trying to understand how multiple routes can lead to the same view/templateUrl and controller. This is what I have written: angular .module('mwsApp', [ 'ngAnimate', 'ngCookies&ap ...

Storing items in a pre-save hook using Mongoose

I have files that I need to generate, but these files include links, so the structure of the file looks like this: const file = { name: 'some name', content: 'some content, type: 'file type', links: [{ path: 'some ...

Issue with JavaScript Date.parse function not functioning as expected

I have implemented a date validation method in my application to check if a given date is valid or not. myApp.isValidDate = function(date) { var timestamp; timestamp = Date.parse(date); if (isNaN(timestamp) === false) { return true; } return ...

The bookdown feature of tufte_html_book, when combined with the csl style, struggles to properly position citations

bookdown::tufte_html_book does not place citations in the margin with csl notes. Here is an example: bookdown::render_book(input = "index.rmd", output_format = "bookdown::tufte_html_book") The csl used comes from: https://raw.githu ...

align a pair of HTML elements

One of the features on my website is a text area where users can input text. <textarea id="realAreaWhereUserTypes"></textarea> In addition to the text area, there is also a hidden input field like this: <input id="hiddenUserInput" /> ...

What is the best way to import assets from an NPM-powered package in a PHP composer-based package?

First and foremost, let's clarify that this is not a question about incorporating an NPM package as a dependency of a Composer package. Direct usage of NPM or a composer plugin can easily solve that issue. If we have loaded an NPM package as a depend ...

What is the best way to enter text into the terminal following the execution of "yarn start"?

While developing a Node chat application, I encountered an issue where I am unable to type anything in the terminal after entering "yarn start". The tutorial I am following shows that the instructor can still input commands in their terminal after running ...

Create objects in the gallery

I recently developed a React Material-UI component using Typescript: <Grid container direction="row" justifyContent="flex-start" alignItems="flex-start"> <Grid item xs={5}> <B ...

The ripples can be found at the bottom of the map, not at the front

Having an issue when working with Globe where Ripple rings are always appearing on the backside of the map, rather than in front of it Referencing the source code from https://github.com/vasturiano/globe.gl/blob/master/example/random-rings/index.html and ...

Error injecting Angular components

Here is the structure of my HTML file: <html> <head> <title>PLD Interaction pattern</title> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/> </head> <body ng-app="myT ...

Using jQuery AJAX to add to a JSON response with the value "d:null"

Hey everyone, I'm encountering a strange issue with my callback function when using the AJAX POST method to call my webservice. The JSON response from the webservice looks like this: Dim ser As New System.Web.Script.Serialization.JavaScriptSerialize ...

Encountering the error "Unable to read the offset property of undefined" during a touch event

I'm currently working on integrating a color picker within an Angular application and have been trying to make it compatible with touchscreens. However, I've encountered an issue within the mousedown handler of the code. The problem arises when i ...