I have problem with Boolean flag.
There is no problem if there's just one button, but with multiple buttons it's problematic. After first click the value of the flag is false. But to change the second button's arrow the flag value true value is needed... and so on...
Please click every button one after another to see what I mean.
How can I solve this issue?
var btn = document.querySelectorAll('.cdi-link');
var flag = true;
for (var i = 0; i < btn.length; i++) {
btn[i].addEventListener('click', function(){
var button = this;
var arrow = button.lastElementChild.lastElementChild;
if (flag) {
flag = false;
arrow.innerHTML = '▼';
console.log(flag);
} else {
flag = true;
arrow.innerHTML = '▶';
console.log(flag);
}
});
}
<button type="button" class="cdi-link">
<div>
<span>click to change the arrow</span> <span class="arrow">▶</span>
</div>
</button>
<button type="button" class="cdi-link">
<div>
<span>click to change the arrow</span> <span class="arrow">▶</span>
</div>
</button>
<button type="button" class="cdi-link">
<div>
<span>click to change the arrow</span> <span class="arrow">▶</span>
</div>
</button>