Creating a collapsible navbar using JavaScript

I have implemented a responsive navbar that shrinks with the page size using @media screen. Everything works well, but I need the navbar to collapse into a vertical drop-down menu when the page size is very small, requiring a click to open.

Unfortunately, I am unable to use Bootstrap due to my current circumstances. Therefore, I can only utilize HTML/CSS and JS for this task.

You can view an example on jsfiddle.

Answer №1

To begin, utilize the @media query to conceal the navigation bar element and transform elements into a list view.

@media screen and (max-width: 850px){
  //replace max width with your width

  ul li {
    display: block;
  }
  ul {
    display: none;
  }


}

The showmenu function toggles the visibility of the navigation bar's elements.

function showmenu()
{
    var x = document.getElementById('myUL');
    if (x.style.display == 'none') {
        x.style.display = 'block';
    } else {
        x.style.display = 'none';
    }
}

Additionally, include a button that triggers the function.

<!DOCTYPE html>
<html lang="en">

<head>
<button onclick='showmenu();'>click me to see menu</button>
  <ul id='myUL'>
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
  </ul>
</head>


</html>

We trust this information is beneficial.

Answer №2

If you want to create a responsive menu for your website, you'll need to incorporate some javascript. I found a great example on w3schools that demonstrates how to achieve this. You can check out the full tutorial here.

The process involves hiding the menu on mobile devices using media queries, adjusting its style, and then revealing it with javascript.

JavaScript is required to enable the menu dropdown toggle functionality, while CSS takes care of the rest.

Feel free to ask any questions in the comments section.

/* JavaScript function to toggle the "responsive" class for topnav when the user clicks on the icon */
function myFunction() {
    var x = document.getElementById("myTopnav");
    if (x.className === "topnav") {
        x.className += " responsive";
    } else {
        x.className = "topnav";
    }
}
/* CSS styling for the top navigation */
.topnav {
    background-color: #333;
    overflow: hidden;
}

/* Styling for links within the navigation bar */
.topnav a {
    float: left;
    display: block;
    color: #f2f2f2;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    font-size: 17px;
}

/* Link hover effects */
.topnav a:hover {
    background-color: #ddd;
    color: black;
}

/* Hide the nav icon on small screens */
.topnav .icon {
    display: none;
}
/* Responsive design for small screens */
@media screen and (max-width: 600px) {
  .topnav a:not(:first-child) {display: none;}
  .topnav a.icon {
    float: right;
    display: block;
  }
}
<div class="topnav" id="myTopnav">
  <a href="#home">Home</a>
  <a href="#news">News</a>
  <a href="#contact">Contact</a>
  <a href="#about">About</a>
  <a href="javascript:void(0);" class="icon" onclick="myFunction()">&#9776;</a>
</div>

Answer №3

Here are some suggestions for you to try and customize based on your needs.

  <!DOCTYPE html>
<html>
<head>
<style>
ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

li {
    float: left;
}

li a, .dropbtn {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a:hover, .dropdown:hover .dropbtn {
    background-color: red;
}

li.dropdown {
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}
</style>
</head>
<body>

<ul>
  <li><a href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li class="dropdown">
    <a href="javascript:void(0)" class="dropbtn">Dropdown</a>
    <div class="dropdown-content">
      <a href="#">Link 1</a>
      <a href="#">Link 2</a>
      <a href="#">Link 3</a>
    </div>
  </li>
</ul>

<h3>Customize the Dropdown Menu in the Navigation Bar</h3>


</body>
</html>

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

Tips for extracting and utilizing the values of multiple checked checkboxes in a jQuery datatable

When a button is clicked, I am trying to retrieve the selected values of multiple rows from the datatables. However, with my current code below, I am only able to get the value of the first selected row. function AssignVendor() { var table = $(assig ...

Using Jest or Mocha alongside Vue: Uncaught SyntaxError: Cannot use import statement outside a module

Update: This post has undergone multiple edits, please refer to this new Stackoverflow post for a clearer explanation of the issue: SyntaxError: Cannot use import statement outside a module when following vue-test-utils official tutorial I have been searc ...

Etiquette for the organization of jQuery functions through chaining and nesting

For developers familiar with jQuery, creating dynamic HTML easily can be done using the following method: var d = $('<div/>') .append('some text') .append( $('<ul/>').append( $('&l ...

Is there a way to ensure the scroll bar remains at the bottom as new data is added?

Hey there Coding Enthusiasts! I'm currently working on developing a chat system and one of the features I'm trying to implement is keeping the scroll bar at the bottom. The goal is to ensure that when someone sends a message, the user doesn' ...

Add an input element to a form fieldset by employing vue

In my form, I have a staged approach with 3 fieldsets that only appear when the "Next" button is clicked. Now, in the third fieldset, I need to add input elements based on keys extracted from an external json object. Data: data: () => ({ c ...

Unexpected resizing of a div due to Vue animation

I'm currently working on a quiz and I'm trying to incorporate some animation effects when users navigate between questions. I've been experimenting with a fade in and out effect, but there seems to be a glitch. Whenever I click the button, t ...

choose a value from a dropdown menu to reset other dropdowns to their default values

I am encountering an issue with my PHP form that consists of 7 dropdown lists. Whenever I select a value from one of the dropdown lists, I want the other 6 to reset to their default values if they were previously opened. I believe using JavaScript is neces ...

Assign the src value from JavaScript to the img tag

I need assistance on how to properly insert the image source I am receiving into the <img/> tag. JavaScript: var aa = document.getElementById("TableImage"+getid).src; alert(aa); Result of the above JavaScript: Now, I would like to place this link ...

Printing feature causing conflicts with other jQuery event listeners

After successfully printing the content of a div on click, I encounter the issue that none of my jQuery events work after canceling the print preview. This seems to happen without requiring a page refresh. I'm puzzled as to why this occurs and would ...

Converting URL for AJAX POST information

While trying to encode a URL using encodeURIComponent, I encountered a 500 SERVER ERROR on certain URLs. It appears that the issue lies in the encoding process, as removing the data resolves the error entirely. What is the correct way to encode the URL to ...

I've noticed that whenever I attempt to update my array in useState using React Hooks, it does indeed work. However, I've also observed that the array seems to

import React,{useState} from "react"; const friendsList = [ { name:"Jack", age: 30, }, { name:"Emily", age: 28, }, { name:"Alex", age: 25, }, ] ...

Uncovering the Solution: Digging into a Nested ng-repeat to Access an Array in AngularJS

I am working with a recursive array in JavaScript: [{ type: 'cond', conditionId: 1, conditions: undefined }, { type: 'cond', conditionId: 2, conditions: undefined }, { type: 'group', conditionId: undefined, ...

Dealing with Sideways Overflow Using slideDown() and slideUp()

Attempting to use slideUp() and slideDown() for an animated reveal of page elements, I encountered difficulty when dealing with a relatively positioned icon placed outside the element. During these animations, overflow is set to hidden, resulting in my ico ...

Storing information within AngularJS

As a newcomer to the world of coding and Angular, I am currently working on developing a calculator-style web application that includes a rating section in the footer. My main concern revolves around saving data so that it can be accessed by other users. T ...

Jquery Datatable failing to display data on screen

For displaying data, I have implemented Jquery Data table using an ajax call and a JSON file. The setup includes two tables - #list1 shows SQL data while #list2 gets populated when a row in the first table is clicked (click event). However, I encountered i ...

Retrieve the targeted row from the table and then employ a function

Here is a datatable that I am working on: http://jsbin.com/OJAnaji/15/edit I initially populate the table with data and display it. Then, I add a new column called "kontrole." data = google.visualization.arrayToDataTable([ ['Name', &apo ...

What is the method to display a navbar exclusively on the product category page?

I am trying to create a navbar that will only show up on the product category page of my Woocommerce website. Is there anyone who can provide me with the necessary PHP or JavaScript code to achieve this? Thank you in advance! Here is the HTML code of the ...

Rails does not appear to have Bootstrap installed

Having trouble with Bootstrap integration, encountering the error message: Sprockets::FileNotFound in Home#index Showing /Users/user/Ruby/app/views/layouts/application.html.erb where line #5 raised: couldn't find file 'twitter/bootstrap/responsi ...

Is there a way to reset back to the default CSS styles?

I have a div container with a nested span element (simplified). <div class="divDash"> <span>XX</span> </div> The CSS styling for the div makes the span initially hidden and only visible when hovering over the parent div. .div ...

Encountering the error message "Uncaught Promise (SyntaxError): Unexpected end of JSON input"

Below is the code snippet I am using: const userIds: string[] = [ // Squall '226618912320520192', // Tofu '249855890381996032', // Alex '343201768668266496', // Jeremy '75468123623614066 ...