How do I use javascript to make one div visible and hide another?

Asked

Viewed 483 times

0

Hello,

I have 3 div’s: one that works as a button and two other as a color box.

I need you to click on div that works as a button to div COLOUR 2 close and the COLOUR 1 be visible.

This one works as a button:

<div onclick="Mudarestado('minhaDiv')">ALTERNAR</div>

These are color boxes:

<div id="minhaDiv" style="display:none;">COR 1</div>
<div id="minhaDiv" style="display:block;">COR 2</div>

Java Script:

<script type="text/javascript">
function confirmadeletar(el) {
        var display = document.getElementById(el).style.display;
        if(display == "none")
            document.getElementById(el).style.display = 'block';
        else
            document.getElementById(el).style.display = 'none';
    }
</script>
  • 1

    did you notice that the id of the Divs are equal? id="myDiv"

  • ideal in this case is to have a single div and then switch the css class each with different style

2 answers

1


The id of divs are equal and you are not calling the function that is in the script, see how it looks after the fixes:

<div onclick="Mudarestado()">ALTERNAR</div>

<div id="minhaDiv1" style="display:none;">COR 1</div>
<div id="minhaDiv2" style="display:block;">COR 2</div>

<script type="text/javascript">
function Mudarestado(el) {
        var display1 = document.getElementById('minhaDiv1').style.display;
        var display2 = document.getElementById('minhaDiv2').style.display;
        if(display1 == "none") {
            document.getElementById('minhaDiv1').style.display = 'block';
            document.getElementById('minhaDiv2').style.display = 'none';
        } else {
            document.getElementById('minhaDiv2').style.display = 'block';
            document.getElementById('minhaDiv1').style.display = 'none';
        }
    }
</script>

1

One <div> making paper buttons is strange and does not help the screen readers nor the semantics of an HTML document.

But anyway, the performative solution would be to use CSS to show/hide <div>s where when placing and taking a class from a parent element the children are shown or hidden.

Below is an example using the methods Element.classList.toggle() and Element.classList.contains() (Docs);

const btn = document.getElementById('alternar')
const elementoPai = document.getElementById('elemento-pai')

btn.addEventListener('click', event => {
    elementoPai.classList.toggle('ativa')
})
#elemento-pai > .uma-div { display: block; }
#elemento-pai > .outra-div { display: none; }

#elemento-pai.ativa > .uma-div { display: none; }
#elemento-pai.ativa > .outra-div { display: block; }

.uma-div { background-color: tomato; }
.outra-div { background-color: gold; }
<button id="alternar">Alternar</button>
<hr>
<div id="elemento-pai">
  <div class="uma-div">Div 1</div>
  <div class="outra-div">Div 2</div>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.