I have 2 groups of HTML, with the same number of elements in each group. The idea is when a button in the 1st group is clicked, it will display the element of the same index in the 2nd group.
There is a caveat however, when I click on a different element in the 1st group, the other elements in the 2nd group gets hidden.
I did come up with a solution below, but it feels impractical, because what if I have infinite elements..
I think it has to do with closures and keeping the index static, but I'm not sure how to approach it..
Thanks in advance
edit: trying to approach this with vanilla JS
HTML
<div class="a-container">
<a href="#">1</a>
<a href="#">2</a>
<a href="#">3</a>
</div>
<div class="b-container">
<p>1</p>
<p>2</p>
<p>3</p>
</div>
Javascript
var a = document.querySelectorAll("a");
var aClick = function(i){
a[i].addEventListener("click", function(e){
showP(i);
});
}
var p = document.querySelectorAll("p");
var showP = function(i) {
p[0].classList.remove("active"); // impractical
p[1].classList.remove("active"); // impractical
p[2].classList.remove("active"); // impractical
p[i].classList.add("active");
}
for (i = 0;i < a.length; i++) {
aClick(i);
}
CSS
a {
display: block;
}
.a-container {
border:1px solid black;
}
.b-container {
border:1px solid black;
margin: 2% 0;
}
p {
opacity: 0;
}
.active {
opacity: 1;
}