Jquery toggle does not work

Asked

Viewed 142 times

1

I’m using the function toggle of jQuery, is working perfectly, but I put 12 Divs with text and when I click to open only one, all are opening.

Follows the code of Javascript:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("span.seta-baixo").click(function(){
        $("p.perguntas-conteudo").toggle();
    });
});

</script>

What I want is this, when I click on a div, will expand the text only from her and when I open the other div with other text information, will close the previous and open only this.

What is happening is that by clicking the button to open the text, opens all div, i.e., the toggle is picking up on all.

  • guy edits the question and cloca tb your HTML code, will make it easy to answer you!

1 answer

0


You can take the class index of the clicked arrow and apply the .toggle in the respective class index .perguntas-conteudo, since each arrow corresponds to a p, then each arrow class index .seta-baixo is the same index as the p .perguntas-conteudo:

$(document).ready(function(){
    $("span.seta-baixo").click(function(){
        // pega o índice da seta clicada dentro da classe
        var idx = $(this).index(".seta-baixo");
        // pega o respectivo <p> pelo índice usando :eq
        var per = $("p.perguntas-conteudo:eq("+idx+")");
        // oculta todos os <p> visíveis exceto o relacionado à seta clicada
        $("p.perguntas-conteudo:visible").not(per).hide();
        // abre ou esconde o respectivo <p> da seta
        per.toggle();
    });
});
.seta-baixo{
   display: block;
}

.perguntas-conteudo{
   display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
   <span class="seta-baixo"><strong>Seta 1</strong></span>
   <p class="perguntas-conteudo">pergunta 1</p>
   <span class="seta-baixo"><strong>Seta 2</strong></span>
   <p class="perguntas-conteudo">pergunta 2</p>
</div>

  • Thanks! Thank you very much

Browser other questions tagged

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