Let's say I have 4 items within a paragraph at the top of the page, that when clicked should open up a "more info" div (say, a popup created by adding "active" class).
But, these divs are not near their trigger, so prev/next/sibling manipulations won't work. Is there a way to trigger them some other way, without writing individual event listeners for each pair? Like some loop way? I'm having trouble getting it to work b/c of closures or scope or something.
<section>
<ul>
<li>click question mark to learn more: <span class="questionmark">?</span></li>
<li>click question mark to learn more: <span class="questionmark">?</span></li>
<li>click question mark to learn more: <span class="questionmark">?</span></li>
</ul>
<div class="tooltip">
<div class="tooltip-inner">
<a class="close-tip">×</a>
1</div>
</div>
<div class="tooltip">
<div class="tooltip-inner">
<a class="close-tip">×</a>
2</div>
</div>
<div class="tooltip">
<div class="tooltip-inner">
<a class="close-tip">×</a>
3</div>
</div>
</section>
and the JS:
var qmks = document.getElementsByClassName('questionmark');
var tooltips = document.getElementsByClassName('tooltip');
var closetips = document.getElementsByClassName('close-tip');
// toggle "active" class on matching tooltip
function openTip(){
tooltips[i].classList.toggle('active');
console.log('works ' + i); // test to see if it's triggering, and what it thinks "i" is.
}
// failed attempt to match nth question with nth tooltip.
for (let i = 0; i < qmks.length; i++) {
qmks[i].addEventListener('click', openTip);
}
for (let k = 0; k < closetips.length; k++) {
closetips[k].addEventListener('click', closeTip);
}
function closeTip(){
for (let j = 0; j<tooltips.length; j++) {
tooltips[j].classList.remove("active");
}
}