Bhavin Shah Bhavin Shah - 3 months ago 12
CSS Question

Show One Div and Hide Another Div when Click on button

What I want to do is, when I click on button then one div should disappear and another should appear and if i click on the same button one more time, then first one should appear and second one should disappear. This would go until I click on the button.

What I tried:

JavaScript:

function change_image(){
var flag = true;
if(flag){
document.getElementById('speaker_main_div_with_rounded_image').style.display="none";
document.getElementById('speaker_main_div_with_square_image').style.display="block";
flag = false;
} else {
document.getElementById('speaker_main_div_with_rounded_image').style.display="block";
document.getElementById('speaker_main_div_with_square_image').style.display="none";
flag = true;
}
}


HTML:

<input type="button" value="Click Here to get another image" onClick="change_image(this)">


Any help would be grateful.

Thank You.

Answer

Your flag variable is local, and its value is always the same when function is called. Initialize it with:

var flag = document.getElementById('speaker_main_div_with_rounded_image').style.display !== 'none';