Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript replace div on each click

The following works to replace a div with a new div...

<div id = "div1" style="display:block" onclick = "replace()"><img src="1.jpg" /></div>

<div id = "div2" style="display:none"><img src="2.jpg" /></div>

<script type = "text/javascript">
function replace() {
document.getElementById("div1").style.display="none";
document.getElementById("div2").style.display="block";
}

</script>

What I can't figure out is how to make this work so when you click div2 it is replaced by div3 and so on.

In other words, I want to replace the div on each click more than just once. What's the best way to go about this? I'm a novice, so not sure if the above is a good start or not.

Thanks!

like image 535
rivitzs Avatar asked Nov 30 '25 16:11

rivitzs


1 Answers

You could make a more generic function:

function replace( hide, show ) {
  document.getElementById(hide).style.display="none";
  document.getElementById(show).style.display="block";
}

Then you can create many divs and use the same function:

<div id = "div1" style="display:block" onclick = "replace('div1','div2')">...</div>
<div id = "div2" style="display:none" onclick = "replace('div2','div3')">..</div>
<div id = "div3" style="display:none" onclick = "replace('div3','div4')">..</div>
...
like image 108
Johno Avatar answered Dec 02 '25 05:12

Johno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!