-1

Trying to create a responsive sidebar, i want some things to be hidden when it's closed, and show when it's opened. I trying to do it with the get, set and remove Attribute, but it doesn't work. The tags already have the hidden attribute in them.

const menu = document.querySelector(".menu");
const sidebar = document.querySelector(".sidebar");
const hidden = document.querySelectorAll(".hiddens");

menu.addEventListener("click", sidebarWidth)

function sidebarWidth(){
    if(sidebar.style["width"] == "5.5vw"){
        sidebar.style["width"] = "18vw";
        show();
    } else {
        sidebar.style["width"] = "5.5vw";
        hide();
    }
}

function show(){
    hidden.getAttribute("hidden");
    hidden.removeAttribute("hidden");
}

function hide(){
    hidden.setAttribute("hidden");
}

Tried using the set, get and remove attribute in the sidebarWidth function, tried creating another event just for them, tried it how it is now, none worked. What's wrong?

Irrobs
  • 1
  • Your `hidden` variable is a [NodeList](https://developer.mozilla.org/en-US/docs/Web/API/NodeList). You can't remove an attribute from the list. – ray Nov 25 '22 at 01:45

2 Answers2

2

Check the API of setAttribute,we will find it needs two parameters,you have missing the second paramter to set it true or false

enter image description here

Also,since hidden is get from document.querySelectorAll it's an array,so it can not call setAttribute directly,we need to iterate one by one

So change to below code

function show(){
    for(let i=0;i<hidden.length;i++){
         hidden[i].setAttribute("hidden",true);
    }
}

function hide(){
    for(let i=0;i<hidden.length;i++){
         hidden[i].setAttribute("hidden",false);
    }
}
flyingfox
  • 13,414
  • 3
  • 24
  • 39
  • Thank you! Had to made some changes for it to work. Changed the setAttribute in th show() function toa removeAttribute("hidden") and in the hide() changed false to true and it worked. Thanks a lot. – Irrobs Nov 25 '22 at 02:23
1

First off, you can use the hidden property of HTMLelements.

Also, the queryselectorAll(".hiddens") function returns an array of all of the elements that are in the .hiddens class.

you need to loop through them like so:

const hidden = document.querySelectorAll(".hiddens");

function show(){
  for(let i of hidden){
    i.hidden= false
  }
}

function hide(){
  for(let i of hidden){
    i.hidden= true
  }
}
Josiah
  • 66
  • 5