Js click event, change div

Asked

Viewed 36 times

1

I’m having trouble changing the Divs I own in HTML.

My idea is that by clicking once, a div is displayed and the other hidden. And if the user clicks again, this div will be hidden and the one that was hidden will be visible. I don’t know what logic I have to apply to this. I thought 2-click event but this is strange because you have to click twice to display the other. It would be if I’m in this, I go to the other and vice versa.

The way I did with the 2 clicks:

var lista1 = document.getElementById('exercicio1e2');
var lista2 = document.getElementById('exercicio3e4')

function mudarExercicios(){
    lista1.style.display="flex";
    lista2.style.display="none";
}

function mudarExercicio2(){
    lista1.style.display="none";
    lista2.style.display="flex";
}

and in html my button:

    <button class="mudarExercicio" onclick="mudarExercicios()" ondblclick="mudarExercicio2()" >
        <i class="fas fa-exchange-alt"></i>
    </button>

Someone can give me a light of which way to go?

  • Where are the elements whose ids are exercicio1e2 and exercicio3e4?

1 answer

2

A simpler way to do this is to create a style that hides the div, and use the method toggle from the class list of the element, it adds a class if it does not exist, or removes if it already exists, hence it is sufficient for display: none.

See more here: https://developer.mozilla.org/toggle

An example running below. Note that the toggle acts on classList, which is the list of classes an element has. Both elements have the class "exercise", and one of them will also have "hide-exercise", which will change between the two:

function mudarExercicios(){
   var lista1 = document.getElementById('exercicio1e2');
   var lista2 = document.getElementById('exercicio3e4')
   
   lista1.classList.toggle("esconder-exercicio");
   lista2.classList.toggle("esconder-exercicio");
}
.exercicio {
  display: flex;
  width: 100%px;
  height: 30px;
  padding: 10px;
  margin: 5px;
  border: solid 1px #000
}

.esconder-exercicio {
  display: none;
}
<div id="exercicio1e2" class="exercicio">Olá, sou o elemento exercicio1e2</div>
<div id="exercicio3e4" class="exercicio esconder-exercicio">Olá, sou o elemento exercicio3e4, tudo bem?</div>

<button class="mudarExercicio" onclick="mudarExercicios()">
   <i class="fas fa-exchange-alt"></i>Mudar Exercicio
</button>

Browser other questions tagged

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