cyberhood
cyberhood

Reputation: 23

adding a close button to accordion

I'm trying to add a close button in each of my accordion panels. This is my script. It doesnt work. Where am i going wrong? Any help will be appreciated!

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function(){
        this.classList.toggle("active");
        this.nextElementSibling.classList.toggle("show");
        $('#close').click(function () {
            $("accordion").accordion({active: false}).click();
        }
    }
}
<div class="accord">

<button class="accordion"><b>one</b></button>
<div class="panel">
something about one

  <div id="close"><a href="#">Close</a></div>
</div>

<button class="accordion"><b>two</b></button>
<div class="panel">
  something about two
  
 <div id="close"><a href="#">Close</a></div> 
</div>

<button class="accordion"><b>three</b></button>
<div class="panel">
something about three

<div id="close"><a href="#">Close</a></div>
 </div>

<button class="accordion"><b>four</b></button>
<div id="foo" class="panel">
something about four

<div id="close"><a href="#">Close</a></div>
</div>


</div>

update: i added my html. hope this makes it easier. thanks in advance!

Upvotes: 1

Views: 553

Answers (1)

The_Black_Smurf
The_Black_Smurf

Reputation: 5269

There's many problems with your code. First thing, an id is suppose to be unique across the entire html so you'll have to change it to replace the id of your close div for a class... or even better, since the click will be made on the <a> tag, you should set a class on those elements

<div><a href="#" class="close">Close</a></div>

The next problem is the way you handle the click events. You didn't specify what ui library your are using but I'll try a generic explanation.

//Select the close elements
$(".close").click(function() {

    var closeLink = $(this);

    //The root of the widget
    var widget = closeLink.closest(".accord");

    //This is the accordion you'll be closing
    var closeAccordion = closeLink.closest(".accordion");

    //The other accordion element (every acordions execpt the closing one)
    var otherAccordion = widget.children(".accordion").not(closeAccordion); 

    //From there you can implement you logic using the variable above

});

As you can see, the code ain't complete but it's a good head start to help you understand how to write dom elements and how to handle them with jquery.

Upvotes: 1

Related Questions