简体   繁体   中英

Having trouble with accordion with Jquery

My accordion works fine but I try to click on an already opened tab and it doesn't close back and also I want my accordion to close as one tab is opened the rest of the other tabs close.

Here is the code:

    $(function(){
  var heading = $('h1');

  heading.on('click', function(event){
    var target = $(event.target);
    $('div.content').addClass('hidden');
  target.next('div.content').removeClass('hidden');

   })
});

Make sure your HTML code is like below,

<h1>Title 1</h1>
<div class="content hidden">
    Title 1 Content
</div>
<h1>Title 2</h1>
<div class="content hidden">
    Title 2 Content
</div>
<h1>Title 3</h1>
<div class="content hidden">
    Title 3 Content
</div>

add this jquery

$(function(){
    // hiding rest of the content block (optional), its already hidden in html code by css class
    $('div.content').addClass('hidden');  
    $('h1').on('click', function(){
        if($(this).next('div.content').hasClass('hidden')){
            $(this).next('div.content').removeClass('hidden').addClass('visible');
        }else{
            $(this).next('div.content').removeClass('visible').addClass('hidden');
        }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM