How to keep a div always active

Asked

Viewed 96 times

1

I have this example that I need you to always have an active div. It gives way that it is possible to disable the three.

<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
    width: 30%;
    padding: 50px 0;
    text-align: center;
    background-color: lightblue;
    margin: 0 auto;
}

#myDIV2 {
    width: 30%;
    padding: 50px 0;
    text-align: center;
    background-color: green;
    margin: 0 auto;
    display: none;
}

#myDIV3 {
    width: 30%;
    padding: 50px 0;
    text-align: center;
    background-color: red;
    margin: 0 auto;
    display: none;
}
</style>
</head>
<body>

<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>

<nav class="columns" id="actions-sidebar">
    <ul class="side-nav">    
        <li><?= $this->Html->link('> '.__('Student Data'),'javascript:myFunctionX()', ['style' => $dataButton]) ?></li>
        <li><?= $this->Html->link('> '.'Trabalho', 'javascript:myFunctionY()', ['style' => $matriculaButton]); ?></li>
        <li><?= $this->Html->link('> '.'Referências','javascript:myFunctionZ()', ['style' => $matriculaButton]) ?></li>
    </ul>
</nav>

<div id="myDIV">
This is my DIV element.
</div>
<div id="myDIV2">
This is my DIV element.
</div>
<div id="myDIV3">
This is my DIV element.
</div>

<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>

<script>
function myFunctionX() {
    var x = document.getElementById("myDIV");
    var y = document.getElementById("myDIV2");   
    var z = document.getElementById("myDIV3");

    if (x.style.display === "none") {
        x.style.display = "block";
        y.style.display = "none";
        z.style.display = "none";

    } else {
        x.style.display = "none";
        y.style.display = "none";
        z.style.display = "none";
    }


}
function myFunctionY() {
    var x = document.getElementById("myDIV");
    var y = document.getElementById("myDIV2");   
    var z = document.getElementById("myDIV3");

  if (y.style.display === "none") {
        x.style.display = "none";
        y.style.display = "block";
        z.style.display = "none";
    } else {
        x.style.display = "none";
        y.style.display = "none";
        z.style.display = "none";
    }
}

function myFunctionZ() {
    var x = document.getElementById("myDIV");
    var y = document.getElementById("myDIV2");   
    var z = document.getElementById("myDIV3");

  if (z.style.display === "none") {
        x.style.display = "none";
        y.style.display = "none";
        z.style.display = "block";
    } else {
        x.style.display = "none";
        y.style.display = "none";
        z.style.display = "none";
    }
}
</script>

</body>
</html>

https://codepen.io/FabricioDev/pen/LOrEGr

  • 1

    Remove the x.style.display = "none" of else of function myFunctionX, the y.style.display = "none" of else of function myFunctionY and the z.style.display = "none" of else of function myFunctionZ. I will not elaborate answer because I am in a hurry, someone will.

3 answers

1

As well as @Gustavocinque said in the comments your code can be arranged like this :

function myFunctionX() {
    var x = document.getElementById("myDIV");
    var y = document.getElementById("myDIV2");   
    var z = document.getElementById("myDIV3");

    if (x.style.display === "none") {
        x.style.display = "block";
        y.style.display = "none";
        z.style.display = "none";

    } else {
        y.style.display = "none";
        z.style.display = "none";
    }


}
function myFunctionY() {
    var x = document.getElementById("myDIV");
    var y = document.getElementById("myDIV2");   
    var z = document.getElementById("myDIV3");

  if (y.style.display === "none") {
        x.style.display = "none";
        y.style.display = "block";
        z.style.display = "none";
    } else {
        x.style.display = "none";
        z.style.display = "none";
    }
}

function myFunctionZ() {
    var x = document.getElementById("myDIV");
    var y = document.getElementById("myDIV2");   
    var z = document.getElementById("myDIV3");

  if (z.style.display === "none") {
        x.style.display = "none";
        y.style.display = "none";
        z.style.display = "block";
    } else {
        x.style.display = "none";
        y.style.display = "none";
    }
}

But as a suggestion from me to cut down on that code I have the following :

Changes in the HTML

<button class="x" onclick="myFunction(this)">Botão 1</button>
<button class="y" onclick="myFunction(this)">Botão 2</button>
<button class="z" onclick="myFunction(this)">Botão 3</button>

I added a class in each button and passed the this as a parameter of the new function.

Changes in the Javascript

//Eu troquei, invés de ter 3 funções uma para cada botão tem apenas 1
function myFunction(el) { 
    // "el" é o elemento que aciona a função 

    var my_class = el.className; 
    // my_class é a classe identificadora que eu tinha criado para essa nova função

    var x = document.getElementById("myDIV");
    var y = document.getElementById("myDIV2");   
    var z = document.getElementById("myDIV3");

    // nesse switch vou verificar qual a class do "el" e assim determinar qual div deve aparecer
    switch (my_class) {

        case "myDIV":
            x.style.display = "block";
            y.style.display = "none";
            z.style.display = "none";
            break;

        case "myDIV2":
            x.style.display = "none";
            y.style.display = "block";
            z.style.display = "none";
            break;

        case "myDIV3":
            x.style.display = "none";
            y.style.display = "none";
            z.style.display = "block";
            break;

        default:
            break;
    }

}

If you have any doubts just leave in the comment that I will try to answer as soon as possible

1


Every time you have too much repeat code means you’re not doing things the right way and you end up making it harder later when you need to change or maintain the code.

You can refactor the code a little using an array for the <div> to show/hide and for each click hide all <div> and then show what was clicked.

Example:

const divs = [...document.querySelectorAll('#myDIV,#myDIV2,#myDIV3')];
const botoes = [...document.querySelectorAll("button")];

for (let i = 0; i < botoes.length; ++i){ //percorrer todos os botoes
  botoes[i].addEventListener("click", function(){ //definir o click para cada um
    divs.forEach(div => div.style.display = "none"); //esconder todos os divs
    divs[i].style.display = "block"; //mostrar o que foi clicado
  }); 
}

divs.forEach(div => div.style.display = "none"); //iniciar todos escondidos
#myDIV {
    width: 30%;
    padding: 50px 0;
    text-align: center;
    background-color: lightblue;
    margin: 0 auto;
}

#myDIV2 {
    width: 30%;
    padding: 50px 0;
    text-align: center;
    background-color: green;
    margin: 0 auto;
    display: none;
}

#myDIV3 {
    width: 30%;
    padding: 50px 0;
    text-align: center;
    background-color: red;
    margin: 0 auto;
    display: none;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>

<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>

<button>Botão 1</button>
<button>Botão 2</button>
<button>Botão 3</button>

<div id="myDIV">This is my DIV element.</div>
<div id="myDIV2">This is my DIV element.</div>
<div id="myDIV3">This is my DIV element.</div>

<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>

</body>
</html>

How you assign the click event directly to javascript made it unnecessary to have the attribute onclick on each of the buttons.

  • Hello. In the line below you start all as hidden. Need the first start enabled. How do I do this? Divs.foreach(div => div.style.display = "None"); //start all hidden

  • 1

    @fabricio_wm You can do so: divs.forEach(div => div.style.display = "none"); divs[0].style.display="block";

  • I am using cakephp and I use list. I have tested your example in Codepen and it is working. Now I need to make it work by list. Do you know how to solve this? Should I finish and open another question?

  • @fabricio_wm "By list" as well ? Can you elaborate a little? It’s probably best to open a new one, but just try to explain a little bit so I can give you a more concrete opinion

  • https://codepen.io/FabricioDev/pen/JOmjEg My difficulty is passing to cakephp

  • 1

    @fabricio_wm This example only has JS. Put a simplified example in the Pastebin with what you are trying to do

Show 1 more comment

0

Assign the same class to 3, and whenever you activate an add an "active" class, start the application with 1 div with that class. So when you are going to fire the event you check if you have any div with the class "active", if it exists and it is not itself follow the process, otherwise return "false"

Browser other questions tagged

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