Sol Sol - 3 months ago 8
Javascript Question

Can't make a class hide by clicking on the toggle?

I've got this script:

$(document).ready(function(){
$(".info").click(function(){
$(this).addClass('active');
$(this).siblings('.conteudo').slideDown(500);
$(this).parents().siblings().children('.conteudo').slideUp(450);
$(this).parents().siblings().children('.info').removeClass('active');
});
});


And here's the HTML:

<div>
<div class="info nome"></div>
<div class="conteudo texto">conteudo</div>
</div>

<div>
<div class="info nome"></div>
<div class="conteudo ls">
<a href="/">adfsdf</a>
<a href="/">adfsdf</a>
<a href="/">adfsdf</a>
<a href="/">adfsdf</a>
<a href="/">adfsdf</a>
</div>
</div>

<div>
<div class="info nome"></div>
<div class="conteudo texto">this is where the content goes</div>
</div>


I want to add the possibility to hide
.conteudo
when the same
.info
class is clicked on. Right now whenever one
.info
class is clicked on, its
.conteudo
class shows up and hides when the next/previous
.info
class is clicked, so I'd like to make it that people can hide the
.conteudo
class by clicking twice on its
.info
class without messing the show/hide effect it already has.

I'm new to jQuery and I'm trying to learn this stuff so please be nice. I've looked for help about this but I couldn't find anything actually helpful. Thank you so much and sorry if I'm wasting your time.

Answer

You can add a check for if you clicked on the active one, and slide up if so:

$(document).ready(function(){
    $(".info").click(function(){
        if ($(this).hasClass('active')) {
            $(this).removeClass('active');
            $(this).siblings('.conteudo').slideUp(450);
        } else {
            $(this).addClass('active');
            $(this).siblings('.conteudo').slideDown(500);
            $(this).parents().siblings().children('.conteudo').slideUp(450);
        $(this).parents().siblings().children('.info').removeClass('active');
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div class="info nome">toggle</div>
  <div class="conteudo texto">conteudo</div>
</div>

<div>
  <div class="info nome">toggle</div>
  <div class="conteudo ls">
    <a href="/">adfsdf</a>
    <a href="/">adfsdf</a>
    <a href="/">adfsdf</a>
    <a href="/">adfsdf</a>
    <a href="/">adfsdf</a>
  </div>
</div>

<div>
  <div class="info nome">toggle</div>
  <div class="conteudo texto">this is where the content goes</div>
</div>