Creating a Dynamic Navigation Bar with CSS and JavaScript

I have encountered an issue with my responsive menubar where the dropdown button does not have any style when clicked.

function myFunction(){
  var x = document.getElementById("myMenubar");
  if (x.className === "menubar"){
    x.className += "responsive";
  }else{
    x.className = "menubar";
  }
}
.menubar{
    position:absolute;
    width:600px;
    margin-left:35%;
    margin-top:4.5%;
    }
    
    .menubar ul{
    overflow:hidden;
    } 
    
    .menubar ul li{
    display:inline-block;
    margin-right:15%;
    list-style-type:none;
    }
    
    .menubar ul li a{
    text-decoration:none;
    color:white;
    }
    
    .menubar ul li.icon{display:none;}
    .menubar ul li a:hover{color:red;text-decoration:none;}
    .menubar ul li a.current{color:red;text-decoration:none;}
    
    @media screen and (max-width:765px){
    .menubar{
    width:130px;
    margin-left:57%;
    }
    .menubar ul li:not(:first-child) {display:none;}
    .menubar ul li.icon{
    float:right;
    display:inline-block;
    }
    }
    
    @media screen and (max-width:765px){
    .menubar.responsive ul{position:relative;}
    .menubar.responsive ul li.icon{
    position:absolute;
    right:0;
    top:0;
    }
    .menubar.responsive ul li{
    float: none;
        display: inline;
    }
    .menubar.responsive ul li a{
    text-decoration:none;
    color:white;
    text-align:center;
    }
    }
<div class="menubar" id="myMenubar">
    <ul>
        <li><a href="#" class="current">Home</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Products</a></li>
            <li><a href="#">Contact</a></li>
                <li class="icon"><a href="javascript:void(0);" onclick="myFunction()">&#9776;</a></li>
        </ul>
    </div>

What could I be doing wrong? I followed a tutorial from http://www.w3schools.com/howto/howto_js_topnav.asp and made some modifications to fit my design, but it seems like the basics should be the same.

Answer №1

To ensure proper styling,

x.className += "responsive";

should be changed to

x.className += " responsive";

Currently, the class assigned is menubarresponsive instead of menubar and responsive.

Answer №2

Just do it!

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

<head>
  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body>

  <nav id="menu" class="navbar navbar-inverse navbar-fixed-top">
    <div class="container-fluid">
      <div class="navbar-header">
        <a class="navbar-brand" href="#">WebSiteName</a>
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span> 
        </button>
      </div>
      <div class="collapse navbar-collapse" id="myNavbar">
        <ul class="nav navbar-nav">
          <li class="active"><a href="#">Home</a>
          </li>
          <li class="dropdown">
            <a class="dropdown-toggle" data-toggle="dropdown" href="#">Page 1 <span class="caret"></span></a>
            <ul class="dropdown-menu">
              <li><a href="#">Page 1-1</a>
              </li>
              <li><a href="#">Page 1-2</a>
              </li>
              <li><a href="#">Page 1-3</a>
              </li>
            </ul>
          </li>
          <li><a href="#">Page 2</a>
          </li>
          <li><a href="#">Page 3</a>
          </li>
        </ul>
      </div>
    </div>
  </nav>
</body>

</html>

Answer №3

Alright, let's identify the errors that need correction:

  1. Your CSS contains an error where .menubar.responsive selects elements with both menubar and responsive classes.
  2. In your JavaScript code, there is a mistake. The property classname should be a string type. So, x.classname += responsive will concatenate the current classname with responsive, resulting in menubarresponsive.
  3. The function myFunction() has not been assigned to any object.

Solution

You have two options: either modify your CSS (which can be time-consuming) or adjust your JavaScript code. I recommend the latter approach. Below is the revised logic for toggling the responsive class:

function myFunction() {
  document.getElementById('myMenubar').classList.toggle('responsive');
}
.menubar{
    position:absolute;
    width:600px;
    margin-left:35%;
    margin-top:4.5%;
}

/* Remaining CSS styles... */
<div class="menubar" id="myMenubar">
        <ul>
            <li><a href="#" class="current" onclick="myFunction()">Home</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Products</a></li>
            <li><a href="#">Contact</a></li>
            <li class="icon"><a href="javascript:void(0);" onclick="myFunction()">&#9776;</a></li>
        </ul>
</div>

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

Sharing data from parent to child components in Vue.js: A guide to passing references

I need some help with this code snippet HTML Code: <div class="col-xs-4"> <h3 class="text-center">Incomplete task</h3> <div class="well" style="max-height: 300px;overflow: auto;"> <ul id="check-list-box" ...

How can I alter the image using the success function in jQuery?

I'm encountering an issue with my jQuery voting script. Everything seems to be working correctly, except for the fact that the image in the success function of the AJAX request is not updating as expected. jQuery: $("a.vote_down").click(function(){ ...

Converting an HTML page into a JSON object by scraping it

Is there a way to convert an HTML page into a JSON object using web scraping? Here is the content of the page: <html><head><title>Index</title><meta charset="UTF-8"></head><body><div><p>[ <a href ...

Error: The object referenced does not have a function called 'findById' within its methods when trying to export

I have come across a number of similar questions on this platform, but most of them seem to be related to HTML. My issue involves encountering an error while submitting a login form in Java. Here is a Very Simple Save Function: var model = require(' ...

Discover the steps to dynamically alter the inclusion of the Bootstrap CSS file within an Angular project

I manage a multi-language website in both English (EN) and Arabic (AR). Currently, I am utilizing Bootstrap CSS from a CDN and adjusting the CDN link based on the selected language. index.html <!DOCTYPE html> <html lang="en"> <h ...

Sending JSON data to the server using jqGrid: A step-by-step guide

[CHANGE] (I couldn't bear to wait 3 hours for an answer): It seems that the issue is not with the jqGrid component, many thanks to TheCodeDestroyer for identifying this. I ran this code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "h ...

Error Uploading File to Cloudinary Platform

I am currently developing a REST API using Express.js. The main functionality of the API involves accepting a video file from the client and uploading it to Cloudinary. Interestingly, when I test the API by returning the file back to the client, everything ...

Interacting with PHP variables in JSON format

I've recently started using JSON to exchange data between pages, but I am facing a challenge that I can't seem to solve. Essentially, my issue lies in one page where I am utilizing jquery's getJSON method to retrieve JSON data from another ...

Concealed HTML element or generated on-the-fly using JavaScript

What is considered the best practice? I have multiple windows on a page: Auth, Execution Result, and Popups. I can display them in two ways: Create them in pure HTML with CSS, set to display: none, and then fadeIn using jQuery. Create the elements ...

Should I utilize Sockets or Ajax for my project?

My Login Script Journey I have a goal in mind - to create a login script using Nodejs. I am currently exploring the options of utilizing sockets or ajax posts for this task. My Progress So Far I have Nodejs installed and have referenced this code in my ...

Transforming the data from my Event Viewer into a sleek and functional HTML table

I am working on a command to extract Event Viewer data and display it in a more user-friendly format. My goal is to convert the output to an HTML table and save it to a text file for inclusion in an email report. Here is what I have so far: $endTime = Get- ...

Creating Dynamic Lists with React Native

<Search ref="search_box" onSearch={this.onSearch} backgroundColor="white" cancelButtonTextStyle={{ color: "red" }} placeholder="Search Food..." ...

What could be causing JQuery Clip to malfunction?

I'm currently exploring the clip function in JQuery to see how it works. Despite my efforts, I'm facing difficulties in getting the function to operate correctly. My intention is to make the image shrink to nothing within a second. Below is a sni ...

The issue with 'DemoCtrl' defined in Angular JS is that it does not correspond to a valid argument

signup.html <div ng-controller="UniqueCtrl" layout="column" ng-cloak="" class="md-inline-form inputdemoBasicUsage" ng-app="inputBasicDemo"> <md-content md-theme="docs-dark" layout-gt-sm="row" layout-padding=""> <div> <md- ...

ReactJS creating trouble with incorporation of CSS in Table

I've noticed some strange behavior with the alignment of my table data. It seems to be all over the place. How can I fix this issue? Is there a way to specify column widths and ensure the text starts from the same position? Take a look at the table b ...

Repeatedly utilizing a drop-down menu

Can a <select> menu be written and utilized in multiple locations on a webpage? For instance: <select id="dm"> <option value="">Select Quantity</option> <option value="less ">50 - 60</option> <option value="me ...

Form a collection using multiple elements

I'm attempting to combine multiple arrays into a single array. For instance : array1= ['Joe','James','Carl','Angel','Jimmy',]; array2= ['22','11','29','43',&apo ...

An issue encountered with res.download() following res.render() in Node.js

Just started working with Node JS and ran into an issue: Error: Can't set headers after they are sent. I've checked my code, and the problem seems to be related to res.download(); Is there a way to display the view without using res.render()? ...

Align the div to the left with text or a paragraph displayed on the right side

Check out my js fiddle below: https://jsfiddle.net/9yj63s3f/ Here is the CSS code snippet: .viddiv{ float:left; width:50%; } .vidholder{ position:relative;height:0;padding-bottom:50%; width:50%; float:left; } iframe{ position:abso ...

troubleshoot using Visual Studio Code

Here's the scenario: I need to debug a project using VS Code. The project is usually started by a batch file and then runs some JavaScript code. Now, I want to debug the JavaScript code, but I'm not sure how to do that. If anyone has any instruct ...