I’m trying to make an extra text-box appear on button press – as I have many separate divs, each one should open its own little box with its own unique text. Right now it only opens the first one as they all share the same ID.
Code example of the current situation:
function myFunction() {
var x = document.getElementById("infoTab");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
.wrapper {
display: grid;
padding-bottom: 400px;
height: 100%;
width: 50%;
background: blue;
padding: 100px;
grid-gap: 10px;
}
.wrapper .item {
display: block;
width: 200px;
height: 200px;
background: green;
padding: 10px;
}
.wrapper .item #infoTab {
width: 100%;
height: 50%;
background: white;
position:relative;
top: 0;
}
.btn {
display: block;
position: relative;
padding: 10px;
}
<section class="wrapper">
<div class="item">
<button type="button" class="btn" onclick="myFunction()">Info</button>
<p>text 1.1</p>
<div id="infoTab" style="display:none;">
<p>text 2.1</p>
</div>
</div>
<div class="item">
<button type="button" class="btn" onclick="myFunction()">Info</button>
<p>text 1.2</p>
<div id="infoTab" style="display:none;">
<p>text 2.2</p>
</div>
</div>
From what I’ve read I understand exactly WHY it’s happening, but I’m clueless on how to make it work with multiple Divs. Sadly my search for the answer was unsuccessful (might be due to my bad terminology).
>Solution :
A solution would be to pass the button as parameter to myFunction() (using this keyword) , get the button parent, find it’s infoTab child (using querySelector(".infoTab") ) when infoTab is a class and not an id, and toggling it’s display:
function myFunction(button) {
var parent = button.parentNode; //parent of button. (<div class="item">)
var x = parent.querySelector(".infoTab");//returns the fisrt child of parent which has infoTab class
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
.wrapper {
display: grid;
padding-bottom: 400px;
height: 100%;
width: 50%;
background: blue;
padding: 100px;
grid-gap: 10px;
}
.wrapper .item {
display: block;
width: 200px;
height: 200px;
background: green;
padding: 10px;
}
.wrapper .item .infoTab {
width: 100%;
height: 50%;
background: white;
position:relative;
top: 0;
}
.btn {
display: block;
position: relative;
padding: 10px;
}
<section class="wrapper">
<div class="item">
<button type="button" class="btn" onclick="myFunction(this)">Info</button>
<p>text 1.1</p>
<div class="infoTab" style="display:none;">
<p>text 2.1</p>
</div>
</div>
<div class="item">
<button type="button" class="btn" onclick="myFunction(this)">Info</button>
<p>text 1.2</p>
<div class="infoTab" style="display:none;">
<p>text 2.2</p>
</div>
</div>