Search code examples
javascripttoggleslidedowntoggleclass

Toggle slide down for faqs


I'm trying to set up a faqs page on the blog and struggling with getting the code right. Here's what I want to do > http://jsfiddle.net/qwL33/

Actually everything is alright but when clicking over the first part (let's suppose this is question 1), its opening up both parts (means both question). HELP.

Here's the code:

    $('#slidetoggle')
      .on('click', function(e) {
        jQuery('.slider').toggle('slideDown');
      });
<div id="slidetoggle">HELLO 1</div>
<div class="slider" style="display: none">Hello there!</div>

<div id="slidetoggle">HELLO 2</div>
<div class="slider" style="display: none">Hello there!</div>


Solution

  • by far this is not the best option, but your problem is that you are copying the same ID (slidetoggle), i have added the same function again and replace the id adding a 2, you can see it in this fiddle https://jsfiddle.net/sw5ohfqv/ the best way would be to create a function that closes all the one visibles, and then opens the one clicked.

       $('#slidetoggle2')
    .on('click', function(e){
        var $this = $(this),
            $slider = $('.slider'),
            isOpened = $slider.is(':visible');
    
        if (isOpened)
        {
            $slider.slideUp();
            $this.text('show fields');
        }
        else
        {
            $slider.slideDown();
            $this.text('hide fields');
        }
    });