Home > Software design >  How include more variables to show and hide icon
How include more variables to show and hide icon

Time:05-18

I Have the following script that works fine just for one div ("dois"), but I want to include another div\variable for this code. How would be this code to work properly for 2 divs?

document.getElementById("_bar_Id_").onclick = function(c) {
  var x = document.getElementById("dois");
  if (x.style.visibility === "hidden") {
  x.style.visibility = "visible";
  } else {
    x.style.visibility = "hidden";
    }
  }

CodePudding user response:

You would have to create another .onclick listener as follows:


document.getElementById("_bar_Id_").onclick = function(c) {
  //for element with id: dois
  let x = document.getElementById("dois");
  if (x.style.visibility === "hidden") {
  x.style.visibility = "visible";
  } else {
    x.style.visibility = "hidden";
    }
  //for element with id: dois2
  x = document.getElementById("dois2");
  if (x.style.visibility === "hidden") {
  x.style.visibility = "visible";
  } else {
    x.style.visibility = "hidden";
    }
  }

This would obviously not scale when you have a lot of elements you need to change on click. So you should have an array of the ids of all the elements you want to listen to and add an event listener for each of them as follows:

const elementIds = ["dois", "dois2", "dois3", "dois4",];

document.getElementById("_bar_Id_").onclick = function(c) {
  for (id of elementIds) {
    const x = document.getElementById(id);
    if (x.style.visibility === "hidden") {
    x.style.visibility = "visible";
    } else {
      x.style.visibility = "hidden";
    }
  }
}

and now whenever you have a new div with and id you want to listen to, you just have to add them to the elementIds array.

Even further improvement would be how you select the items you change the properties of. With the last solution, whenever you need to add another element, you will have to come up with a unique id and add it to the elementIds array.

Alternatively, you could give all the elements you need to change the visibility of a common class such as barClickTarget and use getElementsByClassName to get all elements with that class. Then, now you could just:

HTML

<div >...</div>
<div >...</div>
<div >...</div>

JS

document.getElementById("_bar_Id_").onclick = function(c) {
    const elems = document.getElementsByClassName("barClickTarget");
  for(const x of elems) {
    if (x.style.visibility === "hidden") {
    x.style.visibility = "visible";
    } else {
      x.style.visibility = "hidden";
    }
  }
}

and all you have to do now to add another barClickTarget is to add that to the class of the target element.

  • Related