Toggle sidebar visibility with a button click

Currently, I am working on a sidebar that can collapse and expand when a button is clicked.

If you wish to take a look, I have created a JSFiddle for reference: https://jsfiddle.net/4er26xwp/1/

The challenge I am facing lies here:

document.getElementsByClassName("spanclass").setAttribute("style","opacity:0; -moz-opacity:0; filter:alpha(opacity=0)");

My goal is to adjust the opacity of all spanClasses simultaneously upon clicking the button. The intention is to make the spans visible when the sidebar expands and hidden when it collapses. What could be causing the issue?

UPDATE: I discovered that by executing the following line of code: document

.getElementsByClassName("spanclass")[1].setAttribute("style","opacity:1; -moz-opacity:1; filter:alpha(opacity=100)");
it successfully changed the opacity for one of the spans. However, I am now wondering how I can achieve the same effect for all spans at once.

Answer №1

Try using document.querySelectorAll instead of document.getElementsByClassName . Then you can loop through all classes and apply the desired style, like this:

Alternatively, you can still use document.getElementsByClassName and execute the same loop.

var open = false;

function navAction() {

if (open == true) {
open = false;
var s = document.getElementById("sidebar");
s.className -= " w160";
document.getElementById("main-container").style.marginLeft = "60px";
document.getElementById("main-container").style.transition = "all 0.2s";
var spanclass = document.querySelectorAll(".spanclass");
for (var i = 0; i < spanclass.length; i++) {
        spanclass[i].setAttribute("style","opacity:0; -moz-opacity:0; filter:alpha(opacity=0)");
    }
}

else if (open == false) {
open = true;
var s = document.getElementById("sidebar");
s.className += " w160";
document.getElementById("main-container").style.marginLeft = "160px";
document.getElementById("main-container").style.transition = "all 0.2s";
var spanclass = document.querySelectorAll(".spanclass");
for (var i = 0; i < spanclass.length; i++) {
        spanclass[i].setAttribute("style","opacity:1; -moz-opacity:1; filter:alpha(opacity=100)");
    }
  }
}
body {
  margin: 0;
  height: 100%;
  font-family: "Poppins", sans-serif;
}

#main-container {
  margin-left: 60px; /* Same as the width of the sidenav */
  padding: 0px 10px;
}
  
#sidebar {
  position: fixed;
  z-index: 10;
  left: 0;
  top: 0;
  height: 100%;
  width: 60px;
  background: #fff;
  border-right: 1px solid #ddd;
  /*
  transition: all .3s ease-in-out;
  */
  overflow: hidden;
}
#sidebar img {
  /*
  width: 60%;
  */
  width: 50px;
  height: auto;
  display: block;
  margin-left: 3px;
  margin: 0 auto;
}    
#sidebar a {
  text-decoration: none;
  display: block;
  padding: 20px 20px;
  color: #000000;
  letter-spacing: 1px;
  font-size: 14px;
  font-weight: bold;
  font-family: Arial;
  width: 60px;
  white-space: nowrap;
  /*
  transition: all .2s ease-in-out;
  */
}
#sidebar a span {
  opacity: 0;
  /*
  transition: all .2s ease-in-out;
  */
}
#sidebar.w160:hover a span {
  opacity: 0.2!important;
}
#sidebar.w160 a:hover span {
  opacity: 1!important;
}
#sidebar a:hover {
  background-color: rgba(255, 255, 255, 0.1);
  color: black !important;
  width: 160px;
}

#sidebar a:hover,
#sidebar a.active {
  text-decoration: none;
  background: #f5f5f5;
  color: black;
  width: auto;
}
  
#sidebar a.active {
  background: #e6e6e6;
}

.openbtn {
  font-size: 20px;
  cursor: pointer;
  background-color: #111;
  color: white;
  padding: 10px 15px;
  border: none;
}

.openbtn:hover {
  background-color: #444;
}

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

.w160{
  width:160px!important;
}

/* On smaller screens, where height is less than 450px, change the style of the sidenav (less padding and a smaller font size) */
@media screen and (max-height: 450px) {
  .sidebar {padding-top: 15px;}
  .sidebar a {font-size: 18px;}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">

</head>
<body>
<div id="main-container">
<div id="sidebar">
<a href="newsale.php">➕<span class="spanclass">New Sale</span></a>
<a class="active" href="#">🏠<span class="spanclass">Home</span></a>
<a href="sales.php">🙋‍♂<span class="spanclass">My Sales</span></a>
<a href="account.php">🔧<span class="spanclass">Account</span></a>
<a href="logout.php">🚪<span class="spanclass">Log Out</span></a>
</div>

<div id="main">
  <button class="openbtn" onclick="navAction()">☰ Open Sidebar</button>  
  <h2>Collapsed Sidebar</h2>
  <p>Click on the hamburger menu/bar icon to open the sidebar, and push this content to the right.</p>
</div>
</div>
</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

Troubleshooting jQuery Sortable Issue with Table and Row Width in ASP.NET MVC View

I am facing an issue with jQuery UI sortable while trying to make my table grid sortable. Despite not getting any error messages, the sortable function is not working as expected. I have never utilized this method in a MVC (views/razor) project before. An ...

Looking to slide a form on top of an image carousel in Bootstrap - any tips?

How can I move this form over the "carousel"? <html> <head> <title>test</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http ...

The detected coordinates are offset from the location of the mouse click

Seeking guidance: I need advice on an issue that arises when clicking on the second tooth from right to left, causing the upper teeth to be colored instead: https://i.sstatic.net/czzmc.png Below is a step-by-step explanation of what the code does: 1) T ...

Unable to use innerHTML function on Blogger platform

I am currently working on a basic voting system. It functions perfectly when the two files are in the same location (locally). However, once I publish it on my blogger platform, the system fails to display the results. (When a user clicks to vote, it regi ...

Using Jquery to loop through a function for every select box that is added dynamically

Encountering some challenges with jQuery while attempting to utilize the same function and iterate over select boxes that are dynamically generated with jQuery's clone() method. Here is a snippet of the content being cloned: <select name="expense ...

What is the best way to paginate a dynamically updated data table using AJAX in Laravel?

I'm currently facing an issue with rendering a Blade template in Laravel. The template includes an HTML table populated with data fetched via AJAX, and I need to implement manual pagination using Laravel's LengthAwarePaginator. The main Blade fi ...

ng-enter animation not working for ui-view nested within another ui-view after page reload

It seems like the issue lies with the ng-enter event not being properly triggered in the lowest level of the ui view hierarchy. I'm unsure how to resolve this problem effectively. In my extensive angularjs application, nested sub-views work flawlessl ...

Incorporating FaceBook into a PhoneGap Application

Currently, I am working on integrating Facebook into my phonegap/cordova application. To guide me through the process, I am using the resources provided in this link: https://github.com/davejohnson/phonegap-plugin-facebook-connect/ Even though I have bee ...

Submitting quiz responses through a PHP based form

I am currently facing an issue with integrating forms and a quiz on my website. Individually, both work fine but when combined, they do not function as expected. Specifically, the quiz itself operates correctly, however, it fails to send the results via P ...

Any methods for integrating js.erb files in Ruby on Rails 7?

I've been searching for a while now on how to integrate js.erb files into my Ruby On Rails 7 project, but I haven't been able to find any helpful information. Have js.erb files become obsolete in Rails 7? If so, is there a way to include partials ...

Upon returning to the website homepage from another page, the JavaScript animation ceases

I implemented a unique typewriter animation on my homepage by utilizing code from this source and making minor HTML edits to customize the content. https://codepen.io/hi-im-si/pen/DHoup. <h5> <body>Hello! I am Jane.</body> < ...

What is the best way to implement a front-end CSS style for text instead of a background style?

I have HTML text I want to style with a color like rgba(0,0,0,0.1), but I want the color to appear above or on top of the text, not below or behind it. Issue: How can I accomplish this? (CSS or JavaScript solutions are welcome). Thank you in advance for ...

How can we replicate user input in React for unit testing purposes?

Struggling to unit test a React component that accepts user input, specifically the onChange function within the component. Unable to set the input value despite trying various methods found online. Below is the component under test: class Input extends C ...

What are some ways to integrate the features of ctype.h into JavaScript?

How can glibc's ctype.h be effectively translated into JavaScript? While I believe it is possible, I am struggling to locate the tables and bitshifting operations used in the C source code. What are the best techniques to employ in this situation? isa ...

Include a CSS file from an external JavaScript file

Is there a way to include an external CSS file in an external JS file? I am trying to reference and load Default.css inside Common.js like the image below shows. Any suggestions are greatly appreciated! BB ...

"Learn how to position a div element below the header div and above the footer div while maintaining full height in

Recently delving into the world of reactjs, I find myself facing a challenge with a page that contains 3 distinct blocks formed by divs. Have a look at the layout on my page: My Page This is the code snippet I have worked on: return ( <div> ...

Utilizing Angular Forms for dynamic string validation with the *ngIf directive

I have a challenge where I need to hide forms in a list if they are empty. These forms contain string values. I attempted to use *ngIf but unfortunately, it did not work as expected and empty fields are still visible in the list. How can I address this iss ...

When using Selenium with Java, interacting with checkboxes produces varying results compared to manually clicking on them

I'm encountering an issue with clicking on a specific checkbox that should be checking all the other checkboxes below it (root parameter). Previously, when using the following code on the element: arguments[0].click(); Attempting to use the regular ...

Ways to determine if a website is being accessed from a mobile device or a computer without relying on TeraWurfl technology

After my search on the internet yielded no answers, I decided to post my question here. Is there a method available to detect whether a site is being accessed from a computer or mobile device without using TeraWurfl? I'm looking for a simple code snip ...

The filter function in Material UI data grid does not seem to be functioning properly when using the renderCell method

I'm currently working on a react project that includes a Data Grid. While the filter functionality works well with most fields, it seems to be having issues with the field that utilizes renderCell. Is there a way to enable filtering for the movie titl ...