NN796
NN796

Reputation: 1267

Keep Jquery accordion menu open on current page

I am sure that i will get help in my particular case. No doubt there are many solutions to achieve this but in my case I am unable to achieve it. Following is my code to generate html dynamically using java script.

Edit 1: I just want to keep open the current pan of accordion as per href attribute of anchor tag which is in fact current page URL. This is it.

JS code to generate html:

<script>
  $.ajax({
    url: "/categories",
    type: 'GET',
    success: function(data) {
      var content = "";

      content += '<div id="category-navigation">';
      for (i = 0; i < data.length; i++) {

        content += '<div class="head">';
        content += '<label class="categoryLables">' + data[i].title;
        content += '</label>';

        content += '<div>';
        content += '<div class="boardsMargin">';
        content += '<ul>';

        for (j = 0; j < data[i].assigned_boards.length; j++) {

          content += '<li>';
          content += "<a href='/#categories/" + data[i].id + "/boards/" + data[i].assigned_boards[j].id + "'>";
          content += data[i].assigned_boards[j].name;
          content += '</a>';
          content += '</li>';
        }

        content += '</ul>';
        content += '</div>';
        content += '</div>';
        content += '</div>';
      }
      content += '</div>';

      $("#myNavigation").html("");
      $("#myNavigation").html(content);

      $('.head').accordion({
        heightStyle: "content",
        active: true,
        collapsible: true
      });


    }

  });

 </script>

HTML:

<div class="myNavigation">
</div>

Edit 2: For more clear view, this is picture of my accordion.

accordion

As a side note: I am working in ruby 2.2.1 and rails 4.1

Upvotes: 3

Views: 1862

Answers (2)

Ahs N
Ahs N

Reputation: 8366

You can use localStorage like so:

$(function () {
    $("#accordion").accordion();
    if (localStorage.getItem('active') != null) {
        $($('h3').get(parseInt(localStorage.getItem('active')))).trigger("click");
    }
});

$('h3').click(function () {
    localStorage.setItem('active', $(this).index("h3"));
});

Here is the JSFiddle demo :)

Note: You may also want to read about sessionStorage

Upvotes: 3

K K
K K

Reputation: 18099

Try setting active option in accordion to the index of panels you want to keep open i.e 0,1,2 etc and set collapsible to false

As per the docs:

Integer: The zero-based index of the panel that is active (open). A negative value selects panels going backward from the last panel.

Reference: http://api.jqueryui.com/accordion/#option-active

JS:

$('.head').accordion({
    heightStyle: "content",
    active: 1, //Change this
    collapsible: false
});

Upvotes: 1

Related Questions