I have five anchor tags. I want to display second anchor tag on click of first anchor tag and hide it self and further when click on second anchor tag show third anchor tag and hide itself and so on.
<a href="javascript:void(0)" id="btn0" onclick='showBtn1()' class="w-auto rounded-pill bg-transparent border px-3 py-2 text-decoration-none text-reset suggestion"><?php print(strval($suggestions[0])); ?></a>
<a href="javascript:void(0)" id="btn1" style="display:none" class="w-auto rounded-pill bg-transparent border px-3 py-2 text-decoration-none text-reset suggestion"><?php print(strval($suggestions[1])); ?></a>
<a href="javascript:void(0)" id="btn2" style="display:none" class="w-auto rounded-pill bg-transparent border px-3 py-2 text-decoration-none text-reset suggestion"><?php print(strval($suggestions[2])); ?></a>
<a href="javascript:void(0)" id="btn3" style="display:none" class="w-auto rounded-pill bg-transparent border px-3 py-2 text-decoration-none text-reset suggestion"><?php print(strval($suggestions[3])); ?></a>
<a href="javascript:void(0)" id="btn4" style="display:none" class="w-auto rounded-pill bg-transparent border px-3 py-2 text-decoration-none text-reset suggestion"><?php print(strval($suggestions[4])); ?></a>
<script>
function showBtn1()
{
var btn0 = document.getElementById('btn0');
var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');
var btn3 = document.getElementById('btn3');
var btn4 = document.getElementById('btn4');
if(btn1.style.display == 'none')
{
btn1.style.display = 'initial';
btn0.style.display = 'none';
btn2.style.display = 'none';
btn3.style.display = 'none';
btn4.style.display = 'none';
}
else
{
btn1.style.display = 'none';
btn0.style.display = 'none';
btn2.style.display = 'none';
btn3.style.display = 'none';
btn4.style.display = 'none';
}
}
</script>
2
Answers
Here you go:
In the buttons use
onclick='showBtn(1 up to 5)'
Have fun learning. Read a little about coding principles.
You don’t need to use ID attributes and weird concatenation to accomplish your stated goal. You could bind a single event listener to the parent element that contains the
a
elements and use the event.target property to identify whicha
element invoked the event handler and find that elements index within the nodelist. With that index value you can use simple arithmetic to find the next element or reset index to beginning. The following has, as the original, 5 hyperlinks but could be scaled to any number without modification.