Home > Enterprise >  Javascript: Replace a Shown Div with another Hidden Div with Button onclick
Javascript: Replace a Shown Div with another Hidden Div with Button onclick

Time:02-11

i want to replace a div that is already displayed with another Hidden div with just one click. i don't want it to toggle. below is the code.

<html>

<script type="text/javascript">
function show(elementId) { 
 document.getElementById("surf").style.display="none";
 document.getElementById(elementId).style.display="block";
}
</script>

<div id="mode" style="display: visible;">Display By Default</div>

<div id="surf" style="display: none;">Display On Click</div>
<br/>
<button type="submit" id="submit" onclick="show('surf');" name="submit">Submit</button>
</html>

My desired output should be Display On Click when i click the button.

But right now i'm having both Display By Default and Display On Click showing when i click the button display by default at the top and Display On Click at button. i just want Display By Default to be replaced with Display On Click on same line.

CodePudding user response:

<!DOCTYPE html>
  <html>
  <body>
    <div id="div1" style="display:block">
    <h2>first div</h2>
</div>
<div id="div2" style="display:none">
    <h2>second div</h2>
</div>
<button onclick=show()>click here</button>
</body>
<script>
function show() {
    let div1 = document.querySelector('#div1');
    let div2 = document.querySelector('#div2');

    if (div1.style.display == "block") {
        div1.style.display = "none";
        div2.style.display = "block";
    } else {
        div1.style.display = "block";
        div2.style.display = "none";
    }

  }
</script>
</html>

onclick to hide div1 and show div2, Next click hide div2 and show div1.

CodePudding user response:

You are targeting the wrong element here document.getElementById("surf").style.display="none";. The "surf" should be "mode" instead. This worked for me

function show(elementId) { 
    document.getElementById("mode").style.display="none";
    document.getElementById(elementId).style.display="block";
}
<div id="mode" style="display: visible;">Display By Default</div>
<div id="surf" style="display: none;">Display On Click</div>
<br/>
<button type="submit" id="submit" onclick="show('surf');" name="submit">Submit</button>

  • Related