Reputation: 47
I built a jquery accordion that works perfectly when first coming to the page, however, when I am rerouted to that page with angular the accordion will no longer expand to see its children. My strongest guess is that it has to do with needing to initialize the accordion in the document ready function.
ACCORDION CODE:
<ul class="accordion">
<li>
<a id="portfolioId" class="toggle" href="javascript:void(0);">Portfolio Name</a>
<ul class="inner">
<li class="">
<a id="projectId" href="#" class="toggle">Project Name</a>
<ul class="inner">
<li>
<a id="designId" href="#" class="toggle">Design Name</a>
<ul class="inner">
<li>
<a id="designName" href="#" class="toggle designArea" style="background-image: unset !important;">Design Area</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
SCRIPT CODE:
$(document).on("click", ".toggle", function(e) {
e.preventDefault();
var $this = $(this);
if ($this.next().hasClass('show')) {
$this.next().removeClass('show');
} else {
$this.parent().parent().find('li .inner').removeClass('show');
$this.next().toggleClass('show');
}
});
I am using angular repeats to populate the data and like I said I have zero issues with it when first coming to the page but if I navigate away then come back the script will not add .show back to the element to be expanded.
Any help would be so greatly appreciated!
Upvotes: 0
Views: 71
Reputation: 196002
After some initial comments the fact that it works in 1st, 3rd (odd times the page is visited) implies that the click handler is bound again on each visit to the page.
So the second time the page is visited there are two click handlers and since what they do is toggle the accordion they cancel each other out. The first handler adds the show
class and the second finds it and removes it.
On solution is to unbind the handler before rebinding. (for such cases it is a good idea to namespace the event)
So change the code to
$(document).off('click.accordion-toggle').on('click.accordion-toggle', '.toggle', function(e) {
e.preventDefault();
var $this = $(this);
if ($this.next().hasClass('show')) {
$this.next().removeClass('show');
} else {
$this.parent().parent().find('li .inner').removeClass('show');
$this.next().toggleClass('show');
}
});
A better approach would be to do the unbinding (.off(...)
) when you unload your component (before changing page or other similar moment depending on what you app/page does).
Upvotes: 1