Issues with navigation drawer not functioning

function adjustMenu() {
    var navigation = document.getElementById("myTopnav");
    if (navigation.className === "topnav") {
        navigation.className += " responsive";
    } else {
        navigation.className = "topnav";
    }
}
body {margin:0;}

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

li {
    float: left;
}

.topnav {
  overflow: hidden;
  background-color: #333;
}

.topnav a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

.topnav a:hover {
  background-color: #ddd;
  color: black;
}

.topnav .icon {
  display: none;
}

@media screen and (max-width: 600px) {
  .topnav li:not(:first-child) {display: none;}
  .topnav a.icon {
    float: right;
    display: block;
  }
}

@media screen and (max-width: 600px) {
  .topnav.responsive {position: relative;}
  .topnav.responsive .icon {
    position: absolute;
    right: 0;
    top: 0;
  }
  .topnav.responsive a {
    float: none;
    display: block;
    text-align: left;
  }

}
<!DOCTYPE html>
<html>
<head>
</head>
<body>

<ul class="topnav" id="myTopnav">
  <li><a href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a href="javascript:void(0);" style="font-size:15px;" class="icon" onclick="adjustMenu()">&#9776;</a></li>
</ul>

<div style="padding-left:16px">
  <h2>Responsive Topnav Example</h2>
  <p>Resize the browser window to see how it works.</p>
</div>

</body>
</html>

In the code, when the screen width is less than 600px, only the home tab remains visible, and the other tabs should be accessible through the hamburger icon in the top right corner. However, the icon does not appear as expected. What could be the issue? How can I correct this functionality? Please provide assistance.

Answer №1

While some responses offer a solution based on your existing code, I suggest taking a different approach for various reasons...

  • Utilizing Unobtrusive JS is crucial for better Separation of Concerns (SoC). Keep it separate from the HTML/global scope using the addEventListener() method and, if needed, an IIFE.

  • A mobile-first strategy should be emphasized in CSS design.

  • When using :hover, it's recommended to also include :focus. Navigate through controls using the tab key to understand why this is important - not everyone relies on a mouse.

  • Consider implementing HTML5 semantics for improved structure.

  • Though less urgent, including a "Home" link is still beneficial.

  • Additional tip: Make sure to use appropriate heading levels (h2 isn't the top level).

(function() {
  'use strict';

  var headerEl = document.querySelector('body > header');
  var btnEl = document.querySelector('.menu-btn');

  if(btnEl && headerEl) {
    btnEl.addEventListener('click', function() {
      headerEl.classList.toggle('open');
    });
  }
})();
.page-header {
  background-color: #333;
  color: #f2f2f2;
  overflow: hidden;
}

.page-header a { display: block; }

.page-header a,
.menu-btn {
  color: inherit;
  text-decoration: none;
  font-size: 17px;
  padding: 14px 16px;
}

button.menu-btn {
  border: none;
  background: none;
  cursor: pointer;
}

.page-header a:hover,
.page-header a:focus,
.menu-btn:hover,
.menu-btn:focus {
  background-color: #ddd;
  color: black;
  outline: none;
}

.page-header:not(.open) a { display:none; }
.menu-btn { float: right; }

@media(min-width: 768px) {
  .page-header.page-header a { display: inline-block; }
  .menu-btn { display: none; }
}
<header class="page-header">
  <button class="menu-btn">&#9776;</button>
  <nav>
    <a href="#home">Home</a>
    <a href="#contact">Contact</a>
    <a href="#about">About</a>
  </nav>
</header>

<main>
  <h1>Responsive Topnav Example</h1>
  <p>Resize the browser window to see how it works.</p>
</main>

Answer №2

The primary concern lies in the fact that while you hide the elements in the small state, you fail to display them when adding the .responsive class. I have implemented some modifications for you below:

https://jsfiddle.net/9xxzsypu/

.topnav.responsive li.item:not(:first-child) { display: block!important; }

Answer №3

For your initial media query attempt, consider trying the following:

@media screen and (max-width: 600px) {
    .topnav li:not(:first-child):not(:last-child) {
         display: none;
    }
}

This code snippet hides all list items within the .topnav class except for the first one, effectively hiding the entire hamburger menu as well.

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

attempting to separate negative and positive values using JavaScript

I'm a beginner and looking to create a function that can filter out negative, positive, and zero values in an array. Although I have managed to achieve this using a for loop with hardcoded numbers, I am struggling to convert it into a reusable functio ...

Dynamic double header and footer would be ideal for optimal flexibility

I'm not entirely certain if it's possible, but I am looking for a flexible solution using either flexbox or CSS table layout to create fixed headers and footers like so: ***header one - fixed - dynamic height*** ***header two - fixed - dynamic h ...

Is there a way to automatically make required fields turn red upon form load using model validations in MVC?

After implementing Model validations and remote attribute validation, I noticed that all mandatory fields turn red when the submit button is clicked. Is it possible for all mandatory fields to turn red upon form load instead? ...

Align list items in the center horizontally regardless of the width

I have created this container element: export const Container = styled.section<ContainerProps>` display: flex; justify-content: center; `; The current setup is vertically centering three list items within the container. However, I am now looking ...

Ways to obtain data in JavaScript function from HTML

Struggling to pass the key from a database query in HTML using PHP to a JavaScript function? You're not alone. The challenge lies in passing the field_id to the updateRecords() JS function through the onClick() event of an HTML button. Previously, se ...

Issue with $_POST['projectSubmit'] not functioning as expected

I'm having trouble with echoing a JavaScript script after hitting the submit button. Instead of working, it just closes the modal and refreshes the page. I tried using `if($_POST['projectSubmit'])` instead of enclosing it in `isset()`, but i ...

The state remains constant upon clicking

Below is the code snippet of my component: import React from "react"; import { useState } from "react"; import { Text, SvgContainer, Svg, Flex } from "../lib/styles"; import Modal from "./Modal"; const Credits = () ...

Leveraging server-side HTML templates with ReactJS

I'm having difficulty with Reactjs and rendering components. Essentially, I have standard html templates on the server and I'm attempting to utilize them as JSX components within React. Everything seems to be working fine, except I am unable to ...

Access navigation through Google Maps on an Android device directly from the website

Currently, I am in the process of developing an angular 4 website that fetches a list of latitude and longitude coordinates from the server. One of the key features on this website is a button that takes the user to Google Maps, where a route is constructe ...

I am having trouble understanding why my GraphQL query is not retrieving any data from the WordPress GraphQL API when using SWR

I have created a query to retrieve my WordPress navigation menus using the WordPress graphql plugin along with swr, graphql, graphql-request, and next.js on my local files. When I add the query on the wp-grphql section of my site, I am able to successfully ...

jQuerry's on method fails to respond to newly added elements through the clone() function

I always thought that jquery's on() function would handle events for dynamically added elements in the DOM, such as those added via ajax or cloning. However, I'm finding that it only works for elements already attached to the dom at page load. Cl ...

Adding code containing various Google Maps elements in a fresh browser window using JavaScript

I've encountered an issue while trying to create a new page with a Google map and title based on the button clicked. Interestingly, when I copy/paste the HTML in the "newhtml" variable into an actual HTML file, it works perfectly fine. However, it doe ...

Sending properties of an element to a function within Angular version 4 or 5

Trying to pass attribute values of elements to a function on button click, this is my approach: <div> <ul #list> <li class="radio" *ngFor="let option of options; let j = index" id={{i}}-{{j}} #item> <label><input t ...

Create a custom element in React to detect and encapsulate links

I could really use some assistance with this issue. I have a bunch of text blocks containing links and have been utilizing linkifyjs's React component to automatically wrap the links in anchor tags. However, now I am looking to add a custom button nex ...

What is the best way to center all items in a vertical list of text?

Having trouble aligning elements in my Angular app - specifically date, file total, and file size. When one number has more digits than the others, it throws off the alignment. I've attempted adjusting padding margins and using display properties lik ...

Error: React.js - The specified element type is invalid

After setting up routing using react-router and trying to access the URL, I encountered an error message saying "Element type is invalid." Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for compos ...

A single background image split into several div elements

I am facing an issue regarding the background image placement in multiple divs. When I set the position to fixed, the image repeats when I resize the screen. However, changing it to absolute causes each div to have its own image. Is there a solution to fi ...

The overlay background is not covering the entire height of the container

The CSS includes a .wrapper with the style min-height: calc(50% - 30px), along with an overlay blur div to cover the entire height of the .wrapper element. Here's a link to a Codepen example showcasing this setup: https://codepen.io/palaniichukdmytro/ ...

The drop-down tabs are being covered by my <div> element

I've been struggling with the layout of my website due to issues with the positioning of my div tags. Whenever I hover over the arcade tab or other drop-down menus, they end up behind the div for my movies. I would like to reverse this behavior so tha ...

Creating an object in JavaScript using variables

Is it possible to create an object with keys coming from a variable parameter? Let's say 'prod_id' holds a value, and I want to create an object with key 'prod_id' and value 1. Can this be achieved? If so, how? Thank you! var cart ...