The menu vanishes when the screen size is reduced

Can't figure out why my JavaScript is causing issues with my menu.

I've made a mistake in the JavaScript file, but in general it's working fine. The problem arises when you load the page with a width less than 858px, then click on one of the menu items, and later increase the width - the menu disappears. I want to prevent this from happening.

Here is the JavaScript, HTML, and CSS:

const mediaQuery = window.matchMedia("(max-width: 858px)");

// Check if the media query is true
if (mediaQuery.matches) {
  // function that hides the menu when a "ul li a" is clicked, and displays it again when clicked repeatly
  function hide() {
    document.getElementById("hidden").style.display = "none";

    // simulate a click event for the class "checkbtn"
    document.getElementsByClassName("checkbtn")[0].click();
  }

  // function that shows the menu when you click the hamburguer icon (fas fa-bars)
  function show() {
    document.getElementById("hidden").style.display = "inherit";
  }
} else {
  function hide() {
    document.getElementById("hidden").style.display = "inherit";
    document.getElementsByClassName("checkbtn")[0].click();
  }

  function show() {
    document.getElementById("hidden").style.display = "inherit";
  }
}
// Initial check
handleTabletChange(mediaQuery);
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>test</title>

    <!-- External Fonts -->
    <link rel="preconnect" href="https://fonts.gstatic.com" />
    <link
      href="https://fonts.googleapis.com/css2?family=Ubuntu&display=swap"
      rel="stylesheet"
    />

    <script src="./main.js"></script>

    <!-- Material Design Icons -->
    <link
      href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet"
    />

    <!-- Hamburger Menu Icon -->
    <script src="https://kit.fontawesome.com/a076d05399.js"></script>

    <style>
      /* Styling for the menu */
       Insert your style here...
    </style>
  </head>
  <body id="body">
    <!-- Navigation Menu -->
    <nav>
      <input type="checkbox" id="check" />
      <label for="check" class="checkbtn"
        ><i class="fas fa-bars" onclick="show()"></i
      ></label>
      <label class="logo"><a href="#body">Name</a></label>
      <ul id="hidden">
         Items for the navigation menu...
      </ul>
    </nav>
  </body>
</html>

Answer №1

When you utilize the "hide()" function, it causes the navigation to disappear. For instance, if you specify that clicking on a list element should hide the navigation, removing the "display: none" property will ensure everything functions as intended.

function hide() {
document.getElementById("hidden").style.display = "none";;

// Trigger an auto-click on the "checkbtn" class
document.getElementsByClassName("checkbtn")[0].click();
}

Consider implementing it like this:

const mediaQuery = window.matchMedia("(max-width: 858px)");

// Check if the media query holds true
if (mediaQuery.matches) {
// Function to hide the menu when a "ul li a" is clicked; and reveal it again upon further clicks
function hide() {
// Trigger an auto-click on the class "checkbtn"
document.getElementsByClassName("checkbtn")[0].click();
}

// Function to display the menu when clicking the hamburger (fas fa-bars)
function show() {
document.getElementById("hidden").style.display = "inherit";
}
} else {
function hide() {
document.getElementById("hidden").style.display = "inherit";
document.getElementsByClassName("checkbtn")[0].click();
}

function show() {
document.getElementById("hidden").style.display = "inherit";
}
}
// Initial check
handleTabletChange(mediaQuery);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>test</title>

<!-- Google Fonts link -->
<link rel="preconnect" href="https://fonts.gstatic.com" />
<link
href="https://fonts.googleapis.com/css2?family=Ubuntu&display=swap"
rel="stylesheet"
/>

<!-- Material Design Icons link -->
<link
href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet"
/>

<!-- Hamburger Menu script link -->
<script src="https://kit.fontawesome.com/a076d05399.js"></script>

<style>
/* Styling for the menu */
nav {
background: linear-gradient(
90deg,
rgba(255, 136, 75, 1) 0%,
rgba(254, 72, 64, 1) 100%
);
height: 55px;
width: 100%;
border-radius: 0;
position: fixed;
z-index: 100;
}

label.logo {
color: white;
font-size: 25px;
line-height: 55px;
padding: 0 100px;
font-weight: bold;
}

label.logo a {
color: white;
}

label.logo a:hover {
box-shadow: none;
background: none;
}

nav ul {
float: right;
margin-right: 20px;
border-radius: 0;
}

nav ul li {
display: inline-block;
line-height: 55px;
margin: 0 5px;
}

nav ul li a {
color: white;
font-size: 14px;
padding: 7px 13px;
}
nav ul li a:hover {
background-color: #2c3e50;
transition: 0.5s;
}

.checkbtn {
font-size: 30px;
color: white;
float: right;
line-height: 55px;
margin-right: 40px;
cursor: pointer;
display: none;
}

#check {
display: none;
}

/* Media queries for the menu */
@media (max-width: 952px) {
label.logo {
font-size: 25px;
padding-left: 50px;
}

nav ul li a {
font-size: 16px;
}
}

@media (max-width: 858px) {
.checkbtn {
display: block;
}

ul {
position: fixed;
width: 100%;
height: 100vh;
background: #2c3e50;
top: 55px;
left: -100%;
text-align: center;
transition: all 0.5s;
}

nav ul li {
display: block;
margin: 50px 0;
line-height: 30px;
}

nav ul li a {
font-size: 17px;
}

nav ul li a:hover {
background: linear-gradient(
90deg,
rgba(255, 136, 75, 1) 0%,
rgba(254, 72, 64, 1) 100%
);
box-shadow: inset 0 0 0 25px rgb(254, 72, 64);
}

#check:checked ~ ul {
left: 0;
}
}
* {
padding: 0;
margin: 0;
text-decoration: none;
list-style: none;
box-sizing: border-box;
border-radius: 10px;
transition: all 0.6s;
}
body {
background-color: #2c3e50;
color: white !important;
font-family: "Ubuntu", sans-serif;
}

.cssAnimation:hover {
transform: translateY(10px) !important;
}
</style>
</head>
<body id="body">
<!-- The Menu -->
<nav>
<input type="checkbox" id="check" />
<label for="check" class="checkbtn"
    ><i class="fas fa-bars" onclick="show()"></i
></label>
<label class="logo"><a href="#body">Name</a></label>
<ul id="hidden">
    <li>
      <a href="#" onclick="hide()">Test</a>
    </li>
    <li>
      <a href="#" onclick="hide()">Test</a>
   </li>
     <li>
       <a href="#" onclick="hide()">Test</a>
    </li>
    <li>
      <a href="#" onclick="hide()">Test</a>
    </li>
  </ul>
 </nav>
</body>
</html>

Happy Coding!

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

Struggling to find a solution for your operating system issue?

We are currently attempting to utilize the markdown-yaml-metadata-parser package for our project. You can find more information about the package here. Within the package, it imports 'os' using the following syntax: const os = require('os ...

Is it possible to create a fading effect on an image using a border-radius of 50%?

Struggling with fading out an image that's circular in shape due to the border-radius: 50%. <section id="main"> <h1>Non-Important-Text</h1> <h4> it's all fun and games until you can't find a damn sol ...

The AngularJS directive within a directive is failing to properly initialize the scope value

In my current setup, I am working with a controller that contains the value $scope.colorHex. As an example, I am utilizing the directive colorpickerTooltip, and within its template, I am calling another directive: <colorpicker ng-model="colorHex">&l ...

Ways to verify the input text for content without activating the submit action using only JavaScript

I'm working on creating a unique input effect where the label moves up 100px when the input is focused, and then remains at the top when the user enters a value. If the input is empty and the user clicks outside, the label will return to its original ...

Utilizing API data sharing across AngularJS controllers

I am facing a challenge with my parent controller and its children controllers, as I want them all to share the data fetched from an Api service. Controllers: var app = angular.module('mymodule',[]); app.controller('main', ['$scop ...

How can I ensure the text remains centered within a div, even when there are buttons aligned to the left or

I have a CSS class called .text-align-center that I used to center text. .text-align-center { text-align:center; } However, I noticed that when there is a left or right arrow icon within the <div>, the text does not appear perfectly centered. Is ...

Create a distributive and an NPM package using one source code

Creating small open source tools is a passion of mine, and I strive to provide the best experience for my users. My packages usually consist of just one function, so here's what I aim to offer: A JavaScript file that users can easily add by including ...

Ensure that Bootstrap4 cards are fully stretched to a width of 100%

Does anyone know how to make Card2 and Card3 in Bootstrap4 stretch to 100% width? Card1 defines the total height, but Card2 and Card3 are not taking up the full remaining width. Card1 is already stretched, but Card2 and Card3 are inside a flex column and a ...

Using an if statement within a map function in a React component

I am facing a challenge with using an if statement inside a map function without changing the return value. Here is my code snippet: this.example = this.state.data.map((item) => { return( <div> {if(1 + 1 == 2){ dat ...

Angular routing is failing to redirect properly

After creating a sample Angular app, the goal is to be redirected to another page using the browser URL http://localhost:1800/demo. The index.html file looks like this: <!doctype html> <html lang="en"> <head> <title>Sample Ang ...

Transforming JQuery code into pure Javascript: Attaching an event listener to dynamically generated elements

After exhausting all available resources on stack overflow, I am still unable to find a solution to my problem. I am currently trying to convert the JQuery function below into Vanilla JavaScript as part of my mission to make web pages free of JQuery. How ...

Offering fields for modules, main, and browser that meet the needs of ESM, CommonJS, and bundlers

I have upgraded a number of my published npm packages to include both commonjs and esm builds. Some of these packages are meant for use in both node and the browser, and they are all compiled using webpack or rollup. Additionally, all of them are written i ...

Fresh ajax requests are not clearing the current data displayed in the JSP table

My ajax function retrieves data from a servlet and displays it in the page successfully. However, each time a new ajax call is made, the form appends the new data to the existing results instead of replacing them. I need to reset the current values stored ...

What could be the reason my Angular interceptor isn't minified correctly?

I have come across this interceptor in my Angular project: angular.module('dwExceptionHandler', []) .factory('ExceptionInterceptor', ['$q', function ($q) { return function (promise) { return promise.th ...

Retrieving the length of a Pipe in the parent component using Angular 2

In Angular2, I have created a custom pipe to filter an array based on type ID and year arrays. Here is how it is defined: @Pipe({name: 'highlightedWorksFilter', pure: false}) export class HighlightedWorksFilterPipe implements PipeTransform { tra ...

"Trouble arose when I tried to incorporate additional functions into my JavaScript code; my prompt feature is not

As a beginner in HTML and JS coding, I am working on creating a page that prompts user input for a name and then executes animations using radio buttons. However, after adding functions for radio button changes, my prompt is no longer functioning properly. ...

Adding the location of the onClick event to the hook - a step-by-step guide

Here is the code I am working with: import { MapContainer, TileLayer } from "react-leaflet"; import React, { useState } from 'react'; export default function App() { const [positionLat, setPositionLat] = useState(null); ...

Pass a collection of items from an ASP MVC application to a JavaScript function

For my university coursework, I decided to use ASP MVC. However, I encountered an issue where sending too many AJAX requests was causing the page to load very slowly. To address this problem, I thought about improving it by retrieving arrays from the datab ...

Checking for the existence of a file in JavaScript

I rely heavily on the scripts and images on my website, but the problem is that everything gets saved to the cache. This means that users can't see updates unless they clear their cache or open the site in private browsing mode. I'm working on cr ...

The type 'void | Observable<User>' does not include the property 'subscribe'. Error code: ts(2339)

authenticate() { this.auth.authenticate(this.username, this.password).subscribe((_: any) => { this.router.navigateByUrl('dashboard', {replaceUrl: true}); }); } I'm puzzled by this error message, I've tried a few solu ...