Search code examples
toggletogglebuttonjquery

jQuery toggle to expand/contract all content independent of previous state


file://localhost/C:/Users/kürşat/Desktop/yeni%20site/faq%20-%20Kopya/kopya.html

this is my photography tutorial page. I'm did manage to toggle on/off when someone clicks a question.

What I can't do : the top right button can expand all but it cannot contract all questions. I should contract/expand all even if some of them were previously opened. At first my code was doing the opposite of previous state.

How can I do that?

Here is my code :

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

<link rel="stylesheet" type="text/css" href="styles.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>


<script type="text/javascript">
$(document).ready(function(){
$("li").click(function(){
    $(this).next().toggle("fast");
    $(li).css("background-color","#999");
    $(article).css("background-color","#FDFEE9");
});
$(document).ready(function(){
$("#expand").click(function(){


     $("article").toggle(true);
     $(this).text($(this).text() == 'Genişlet' ? 'Küçült' : 'Genişlet');
});

$("article").toggle();
});

}); 
</script>


</head>

<body>
    <div  id="page"><h1>Temel Fotoğrafçılık Bilgileri<button id="expand">Genişlet</button></h1>




  <div class="faq"> 
    <!-- The FAQs are inserted here -->
<ul>
    <li>question 1?</li>
     <article> <p>answer 1.</p></article>

  <li>question 2?</li>
     <article> <p>answer 2.</p></article>

  <li>question 3?</li>
     <article> <p>answer 3.</p></article>
</ul>
</div>
</body>
</html>

Here is the working JSfiddle version:

http://jsfiddle.net/reJu9/


Solution

  • Change the expand click callback to

    $("#expand").click(function(){
         var $this = $(this);
         if($this.text() == 'Genişlet')
            $('article').show();
         else
            $('article').hide();
         $this.text($this.text() == 'Genişlet' ? 'Küçült' : 'Genişlet');
    });
    

    Demo: http://jsfiddle.net/joycse06/reJu9/1/