2

I have two buttons defined with their IDs : but-toggle, but-close for show hide a panel :

<button id="but-toggle">Panel</button>
<div id="main-panel" style="display:none">
   <button id="but-close">X</button>
   <!-- some panel data -->
</div>

Now i have a JS function which toggle the panel (show/hide) assigned to but-toggle as following :

(function(){document.getElementById("but-toggle").addEventListener("click",function(){
var pan = document.getElementById("main-panel");
if(pan.style.display==="inline-block")
{pan.style.display="none"}
else
{pan.style.display="inline-block"}
});})();

My question is how to use the same function for both buttons without writing two func, one for each. I want a solution for elements based on their ids, since the classes are differents and can't use getElementByClass for this

Thanks

Stalkium
  • 148
  • 1
  • 11

2 Answers2

2

You can use the below to get all buttons

 var btns=document.getElementsByTagName('button');
     
 for (let i = 0; i < btns.length; i++) {
   btns[i].addEventListener("click", function() {
     //code
   });
 }
     

(OR)

if you use input tag with type button

 document.querySelectorAll("input[type=button]");

(OR) Based on multiple IDs

document.querySelectorAll('#id1, #id2, #id3');

then you can add eventListener

2

You can use document.querySelector to get a list of elements from a list of IDs:

function toggleFn() {
  const pan = document.getElementById("main-panel");
  if(pan.style.display === "inline-block") {
    pan.style.display = "none";
  } else {
    pan.style.display = "inline-block";
  }
}
document.querySelector("#Id1, #Id2")
  .forEach(elem => elem.addEventListener(toggleFn);
Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59
  • Sorry guys both of you posted the correct answer with querySelector("#Id1, #Id2") ..... I was only able to decide between you with FIFO algorithm, pablo posted first, thanks for both of you – Stalkium Mar 15 '21 at 12:31