Toggle script automatically wrapped

I have code

<script>
jQuery(function($) {
      $('#toggle1').click(function() {
        $('.toggle1').slideToggle('slow');
                    return false;
      });
      $('#toggle2').click(function() {
        $('.toggle2').slideToggle('slow');
                    return false;
      });
</script>
      

<a href="#" id="toggle1">header1</a>
<div class="toggle1" style="display:none">content1</div>
<a href="#" id="toggle2">header2</a>
<div class="toggle2" style="display:none">content2</div>
      

Run codeHide result


What should I change to get the result when you click on the first heading, the second is automatically collapsed and vice versa

+3


source to share


4 answers


For this you need toggle () .

Example:



 $('#toggle > a').click(function () {
     var divs = $(this).siblings('div'),
         div = $(this).nextAll('div:first');
     divs.not(div).hide('500');
     div.toggle('500');
 });

      

Demo - JSFiddle

+2


source


jQuery(function($) {
      $('#toggle1').click(function() {
        $('.toggle1').slideToggle('slow');
                    return false;
      });
      $('#toggle2').click(function() {
        $('.toggle2').slideToggle('slow');
                    return false;
      });
  });
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" id="toggle1">header1</a>
<div class="toggle1" style="display:none">content1</div>
<a href="#" id="toggle2">header2</a>
<div class="toggle2" style="display:none">content2</div>
      

Run codeHide result


Check the above code.



Where are you doing wrong:

  • You cannot include any jQuery library.
  • You've added <script>

    JS to your console that shouldn't be there.
  • You forgot to close the function jQuery(function($) {

    with the help });

    at the end.
+1


source


<script>
$(document).ready(function(){
    var $togglers = $('.toggler');
      $togglers.click(function(e) {
          e.preventDefault();
        $togglers.next().slideUp(800);
        $(this).next().slideDown(800);
      });
});
</script>
      

a + div {display:none;}
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" class="toggler">header1</a>
<div>content1</div>
<a href="#" class="toggler">header2</a>
<div>content2</div>
      

Run codeHide result


+1


source


Try,

HTML:

<a href="#" class="toggle" id="toggle1">header1</a>
<div class="toggle1 toggleElem">content1</div>
<a href="#" class="toggle" id="toggle2">header2</a>
<div class="toggle2 toggleElem" style="display:none">content2</div>

      

JS:

$('.toggle').click(function () {
  var currnt = $(this).next(".toggleElem").slideToggle("slow");
  $(".toggleElem").not(currnt).slideUp("slow");
});

      

http://jsfiddle.net/Lj62macr/

0


source







All Articles