JavaScript (Create a button that toggles the visibility of an element)

I have implemented a hamburger menu that transforms into an x when clicked. I am looking to modify it so that clicking on the hamburger opens the menu, and clicking on the x closes the menu.

Below is the code I have been working with:

<!DOCTYPE html>
<html>
<style>
body {
    font-family: "Lato", sans-serif;
}

.sidenav {
    height: 100%;
    width: 0;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: #111;
    overflow-x: hidden;
    transition: 0.5s;
    padding-top: 60px;
}

.sidenav a {
    padding: 8px 8px 8px 32px;
    text-decoration: none;
    font-size: 25px;
    color: #818181;
    display: block;
    transition: 0.3s
}

.sidenav a:hover, .offcanvas a:focus{
    color: #f1f1f1;
}

.closebtn {
    position: absolute;
    top: 0;
    right: 25px;
    font-size: 36px !important;
    margin-left: 50px;
}

#main {
    transition: margin-left .5s;
    padding: 16px;
}

@media screen and (max-height: 450px) {
  .sidenav {padding-top: 15px;}
  .sidenav a {font-size: 18px;}
}
.container {
    display: inline-block;
    cursor: pointer;
}

.bar1, .bar2, .bar3 {
    width: 35px;
    height: 5px;
    background-color: #333;
    margin: 6px 0;
    transition: .9s;
}

.change .bar1 {
    -webkit-transform: rotate(-45deg) translate(-9px, 6px) ;
    transform: rotate(-45deg) translate(-9px, 6px) ;
}

.change .bar2 {opacity: 0;}

.change .bar3 {
    -webkit-transform: rotate(45deg) translate(-8px, -8px) ;
    transform: rotate(45deg) translate(-8px, -8px) ;
}
</style>
<body>

<div id="mySidenav" class="sidenav">

  <a href="#">...</a>
  <a href="#">...</a>
  <a href="#">...</a>
  <a href="#">...</a>
</div>

<div id="main">
  <span style="cursor:pointer" onclick="openNav(); closeNav()>
<div class="container" onclick="myFunction(this)">
  <div class="bar1"></div>
  <div class="bar2"></div>
  <div class="bar3"></div>
</div>
</span>
</div>

<script>
function openNav() {
    document.getElementById("mySidenav").style.width = "250px";
    document.getElementById("main").style.marginLeft = "250px";
}

function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
    document.getElementById("main").style.marginLeft= "0";
}
function myFunction(x) {
    x.classList.toggle("change");
}
</script>

</body>
</html>

Answer №1

If you want to implement a toggle feature, one way you could do it is by using the following function:

function toggleNavigation() {
    var sidebar = document.getElementById("mySidebar"),
    content = document.getElementById("content");
    sidebar.style.width = sidebar.style.width === "250px" ? '0' : '250px';
    content.style.marginLeft = content.style.marginLeft === "250px" ? '0' :  '250px';
}

HTML:

<span style="cursor:pointer" onclick="toggleNavigation();">...</span>

See it in action here: https://jsfiddle.net/iRbouh/df4cuet5/

Answer №2

To easily solve this issue, consider assigning two classes to the button. For example: class="Original Open" where one class is Original and the other is Open.

In your Javascript file, create an onclick function for the Open class that first locates the Original class. Within this onclick function, reveal the Menu Container, add a new class like "Close" to the button when it's clicked for the first time, and remove the "Open" class.

Next, develop an onclick function for the "Close" class that hides the Menu and removes the "Close" class while reinstating the "Open" class.

That's the simple logic behind it...!!

Answer №3

Here is my preferred method.

$(".tab").on("click", function(){
  $(this).toggleClass("active inactive");
});

See it in action: https://example.com/code-demo/

Answer №4

function toggleSidenav(x) { document.getElementById("mySidenav").classList.toggle("open");
    x.classList.toggle("change");
}
body {
    font-family: "Lato", sans-serif;
}

.sidenav {
    height: 100%;
    width: 0;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: #111;
    overflow-x: hidden;
    transition: 0.5s;
    padding-top: 60px;
}

.sidenav a {
    padding: 8px 8px 8px 32px;
    text-decoration: none;
    font-size: 25px;
    color: #818181;
    display: block;
    transition: 0.3s
}

.sidenav a:hover, .offcanvas a:focus{
    color: #f1f1f1;
}

.closebtn {
    position: absolute;
    top: 0;
    right: 25px;
    font-size: 36px !important;
    margin-left: 50px;
}

#main {
    transition: margin-left .5s;
    padding: 16px;
}

@media screen and (max-height: 450px) {
  .sidenav {padding-top: 15px;}
  .sidenav a {font-size: 18px;}
}
.container {
    display: inline-block;
    cursor: pointer;
}

.bar1, .bar2, .bar3 {
    width: 35px;
    height: 5px;
    background-color: #333;
    margin: 6px 0;
    transition: .9s;
}

.change .bar1 {
    -webkit-transform: rotate(-45deg) translate(-9px, 6px) ;
    transform: rotate(-45deg) translate(-9px, 6px) ;
}

.change .bar2 {opacity: 0;}

.change .bar3 {
    -webkit-transform: rotate(45deg) translate(-8px,, -8px) ;
    transform: rotate(45deg) translate(-8px, -8px) ;
}

/* ----- START -----  */

.open {
  width: 250px;
}
.open ~ #main {
  margin-left: 250px;
}

/* ----- END ----- */
<div id="mySidenav" class="sidenav">
  <a href="#">...</a>
  <a href="#">...</a>
  <a href="#">...</a>
  <a href="#">...</a>
</div>

<div id="main">
  <span style="cursor:pointer">
    <div class="container" onclick="toggleSidenav(this)">
      <div class="bar1"></div>
      <div class="bar2"></div>
      <div class="bar3"></div>
    </div>
  </span>
</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

GET method returns an empty array in the express node server

app.get('/:user/:tag', function (req, res) { fs.readdir( 'api'+path.sep+req.params.user, function (err, files) { var tweets=[]; for (var i =1, j=files.length ; i <j; i++) { fs.readFile('api'+path.sep+ ...

The functionality of `req.isAuthenticated()` is never true when using PassportJs with a combination of nodeJS and dynam

I am entering the world of web programming and tasked with creating an Instagram-like platform for my school. The frontend is built in ReactJS and now it's time to develop a server in nodeJS, utilizing passport for authentication and dynamoDb for data ...

Are you interested in implementing the switcher function in a React JS class component?

I am having trouble implementing the switcher method in my react app, which is built using class components. Can you provide guidance on how to utilize the useThemeSwitcher() function in class components? How can I integrate this function into my web app ...

Connect the blade.php file with CSS in Laravel version 5.x

I placed my view.blade.php file in resources\views\admin\login\view.blade.php and used the following code to link it to the CSS file: <link href="{!! HTML::style('css/style.css') !!}" rel="stylesheet">. My CSS file is lo ...

What steps can I take to resolve this CSS problem?

I'm trying to create a box around specific html elements, but the current code is causing each element to be enclosed individually. I don't want to use the html or body element as I have other elements that need to remain outside of the box. h1, ...

Understanding the user's preference for text alignment and managing how the text is displayed in a text area (or text field) within a ReactJS application

My latest project is an app that features multiple text areas. Personally, I use the app with two languages - English and another language that is aligned to the right. However, the default setting has the text-areas aligning to the left. To change this ...

I am utilizing Vuex to store all of the product details and handle API request queries efficiently

Question regarding Vue/Vuex efficiency and best practices. I am working with an API that returns a paginated data-set of 50 products, which I am storing in a Vuex store. When displaying all products, I iterate over the Vuex store. Now, for individual pr ...

Is there a way to place a badge alongside a carousel using Bootstrap?

No matter what I try, I can't seem to get this badge to align properly next to a carousel. I've experimented with the col-md-6 structure for each div, but it doesn't make any difference. I've also attempted using inline-block, but that ...

The compatibility between cross-fetch and React Native is currently not supported

I have developed an API wrapper that utilizes fetch to carry out the API requests. To ensure compatibility with Browsers, Node, and React Native, I incorporate cross-fetch. When testing the wrapper in Node, everything works fine. However, when using it in ...

Morris.js is throwing an error message, stating "Uncaught TypeError: Unable to access the 'label' property as it

I have successfully implemented a bar chart along with a date picker using Bootstrap. The bar chart loads data accurately when selecting a specific day. However, upon inspecting the developer tools, I encounter the following errors: Uncaught Type Error: C ...

Enhancing the efficiency of JavaScript code

Imagine you have a web application processing 1,000,000 user logins per hour. and the code below is executed during each user login: if (DevMode) { // make an Ajax call } else if (RealMode) { // make another Ajax call } else { // Do something ...

Definition for TypeScript for an individual JavaScript document

I am currently attempting to integrate an Ionic2 app within a Movilizer HTML5 view. To facilitate communication between the Movilizer container client and the Ionic2 app, it is crucial to incorporate a plugins/Movilizer.js file. The functionality of this f ...

Having trouble with making a POST request in Node.js using Express.js and Body-parser?

Just starting out with nodejs and currently in the learning phase. I've encountered an issue where my POST request is not functioning as expected. I set up a basic html form to practice using both GET and POST requests. Surprisingly, the GET request w ...

Erroneous deletion issue in React list causing removal of incorrect item

While working on creating a todo list in React, I faced an issue when trying to implement a delete function. The problem arose when attempting to delete an item - instead of removing the selected item, React ended up deleting everything except that specif ...

The useEffect alert is triggered before the component is re-rendered

Can someone help me understand why the HP in the code below is displayed as "1" when the alert is thrown, and only set to "0" after I confirm the alert? Shouldn't the component be rerendered before the alert is thrown so that it has already been displ ...

Having trouble displaying my klout score with ajax

I'm attempting to showcase a Klout score on a webpage Here's my code: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> var settings = { "url": "http://api.klout.co ...

Storing files in DynamoDB using Reactjs is a convenient and efficient way

Is there a way to store resume files in an existing DynamoDB table that currently stores name and email information? I have attempted to do so using React's AWS package with the following code: <input name="my_file" onChange={e => upd ...

Having difficulty accurately interpreting the input value

As someone new to JavaScript, I set out to create a basic calculator using JavaScript and HTML. My goal is to have two input fields, named Fld1 and Fld2, that would add up the values entered into them when submitting. However, despite parsing the input val ...

Concealing Bootstrap 3 elements on a split-screen layout

I encountered a peculiar issue with Bootstrap 3. When I resize my browser width to half the screen, there is a slight 1px threshold where both "hidden-xs" and "hidden-sm" elements become visible simultaneously. Is there a way to fix this so that only one o ...

JavaScript accordions failing to open

I've encountered an issue with my website that includes JS accordions. Strangely, they are not opening on the live site, but they function properly on Codepen. I checked the console in Chrome and found no error messages, however, when I looked at the ...