Using one button to toggle between opening and closing the navigation bar (2 separate functions)

Whenever I try to open or close my navigation bar, I have to use two separate JavaScript functions: openNav() to open and closeNav() to close.

openNav() - open
closeNav() - close

The code for the navigation bar functionality is sourced from W3-schools at http://www.w3schools.com/howto/howto_js_sidenav.asp.

I am looking for an easy way to toggle between opening and closing the navigation bar with the same button. Should I change the onclick="" value each time the button is pressed, or should I use two buttons that hide each other when one is pressed?

Here is the current script:

<script>
function openNav() {
    document.getElementById("nav").style.width = "140px";
    document.getElementById("tabs").style.width = "70%;
    document.getElementById("nav").style.borderRight = "2px solid #0bb1ff";
}

function closeNav() {
    document.getElementById("nav").style.width = "0";
    document.getElementById("tabs").style.width = "80%";
    document.getElementById("nav").style.border = "0";
}
</script>

Button code:

<div class="drop-menu" id="menu" onclick="openNav();"><i class="fa fa-bars" aria-hidden="true"></i></div>

Answer №1

One solution is to create a toggleNav function that checks the current state of the navigation bar and either opens or closes it accordingly:


var navBarOpen = true;
function toggleNav() {
 if (navBarOpen) {
   // close it 
   navBarOpen = !navBarOpen;
 else { 
  // open it 
  navBarOpen = !navBarOpen;
 }

This approach should work well, just make sure to place the code in the appropriate sections of your project.

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

Passing a JavaScript variable to a URL parameter can be achieved by

Can anyone advise me on passing JavaScript string variables and displaying them in the URL? For instance, let's say the URL is "xyc.com". Upon populating a variable (a), I wish for that variable to appear in the address bar as URL = "xyc.com/?a=". Cur ...

How can I position 7 images absolutely within a specific div?

I've been working on a website where users can have their avatars displayed using a JS function that loads 7 different images onto the page. These images correspond to different elements such as skin base, hair, eyes, mouth, shirt, shoes, and pants, a ...

Revise the modal window

I need help with switching between two modal windows for registration and login. How can I make the modal window change when the "Sign Up" button is clicked? Here is the link to my project: https://jsfiddle.net/Alienwave/0kqj7tr1/4/ Vue.component('s ...

The error message thrown is: "Unable to assign headers after they have already been sent to the client."

I've been attempting to make a GET request, but it keeps failing at the app.js res.json line. app.js app.use(function(err, req, res, next) { res.locals.message = err.message; res.locals.error = req.app.get("env") === "development" ? err : {}; ...

Looking to include a data-* attribute within a div element for the utilization of a third-party JavaScript library like React or Next.js?

let speed = '{ "speed": 0.2 }'; <div className="section jarallax h-100vh" data-jarallax={speed} style={{backgroundImage: "url('/images/header-bg.jpg')"}} id="home"> </div> <Script src="./js/parallax.js" strate ...

Chrome experiencing issues with jQuery AJAX, not related to cross-domain problems

I have a simple JS/jQuery code that makes an AJAX call to retrieve some HTML and insert it into a div on my webpage. While this process works smoothly in Firefox, it encounters a failure in Chrome. Upon checking the Chrome console, I can see the AJAX requ ...

Using Flask to trigger a Python function that requires input parameters when a button is clicked

I am working on a Flask web application that includes a download button. Instead of triggering a JavaScript function, I want the button to execute a Python method. This Python method should take the recently modified HTML code from the webpage as input. H ...

Is it possible to decrement the index of an array by 1 and seamlessly loop back to the end in just one line of code?

Imagine I am manually adjusting the index of an array in JavaScript. I have functions to increase and decrease the index, with the goal of looping back to the beginning or end of the array when reaching the limits. While the increase function can be writte ...

Attempting to assign a class name to the <a> tag proves challenging as it seems to reset upon clicking the link, causing the class to vanish

Looking at this HTML code snippet <li> <a href="javascript:;"><i class="sidebar-item-icon ti-hummer"></i> <span class="nav-label">Product Management</span><i class="fa fa-angle-left arrow"></i>&l ...

Firebase Functions: Your functions are missing a definition

I have the following code in index.js: exports.makeUppercase = functions.database.ref('/messages/{pushId}/original').onCreate((snapshot, context) => { // Fetch the current value written to the Realtime Database. const original = snapshot. ...

Create a division that will remain visible on the screen and allow scrolling when a certain class is

Having some trouble with a fixed class div that is not continuing to scroll after the class is removed on scroll. I've attempted to fix this issue but the div keeps getting hidden instead of continuing to scroll. If anyone has any advice or can poin ...

Maximizing the utility of JQuery UI Autocomplete in ASP.NET for optimal efficiency

Incorporating JQuery UI Autocomplete into my ASP.NET-C# Website has been a success. Here is the JavaScript code: $(function () { var availableTags = [ <%=GetAvaliableTags() %> ]; $("input.tag_list").autocomplete( ...

Modifying the Readonly Attribute of an ASP.NET Web Application with the Power of JQuery

Check out this snippet of HTML code <td style="width: 4pt;"> </td> <td> <span style="display: inline-block; color: Black; font-family: Arial; font-size: 9pt; font-weight: normal; width: 100pt; vertical-align: top;"> ...

The Chrome browser on iOS does not fire the Image onLoad event

In my web application, I am utilizing Scala.js and d3.js (scala-js-d3) to generate an SVG. However, I have encountered a problem with the background image not triggering the load event when using Chrome on iOS (iPhone), even though it works fine on Windows ...

Preview your uploaded image before finalizing

I am currently working on implementing a new upload feature for users of our forum. This feature will allow them to upload a personal picture. Here is what I have developed so far: HTML <label>Profile image</label> <div class="phot ...

Trouble getting CKeditor to work properly with Meteor

Previously, the ckeditor was working perfectly in an older version of meteor. However, once I updated the meteor version, the ckeditor stopped working and a textarea is now showing up instead. The console is displaying the following error message:- ...

How to access iFrame in ReactJS using document.getElementById

I am facing a challenge on my website where I need to transfer data (using postMessage) to an iframe. Typically in plain JavaScript, I would use techniques like document.getElementById or $("#iframe") in jQuery to target the iframe. However, I am unsure ...

Java Script Event Handling Creating Array with Numerous Duplicates

While attempting to recreate the Simon game, I am working on adding click events to an array and testing that Array in a nested function immediately. Initially, everything seems to be functioning correctly. However, after the third run, the array does not ...

Invoke the render function once more at the highest level while preserving the ability to make changes

Below is a test that ensures the component is pure (using the PureRenderMixin). However, I'm receiving the following warning message. Warning: setProps(...) and replaceProps(...) are deprecated. Instead, call render again at the top level. it(& ...

Adjusting the orientation of a vector worldwide using a quaternion in THREE.js

Is there a way to set the absolute global rotation of a vector using a quaternion? Imagine a function called f(v, q) which rotates vector v to quaternion q. While THREE.Vector3 has a .applyQuaternion function for applying rotations to vectors, this is a ...