script slows down with repeated use
I wrote a simple jQuery script to take a HTML list (ul and li elements) and add collapsing functionality. The problem is that when you click one of the items open and closed repeatedly, the execution gets slower and slower and eventually stops responding. What could be the problem? Memory leak??
The list is structured like this:
-
<ul class="tree">
<li class="tree">I'm at the top
<ul class="tree">
<li class="tree">I'm item 1 at the second level
<li class="tree">I'm item 2 at the second level
<ul class="tree">
<li class="tree">I'm item 1 at the third level
</ul>
</ul>
</ul>
Here is the javascript:
-
function setclickoff() {
$('span.clickoff').click(function() {
var li = $(this).parent();
$('ul.tree', li).each(function() {
$(this).hide();
});
$(this).html('-');
$(this).attr("class", "clickon");
setclickon();
});
}
function setclickon() {
$('span.clickon').click(function() {
var li = $(this).parent();
var ul = li.parent();
$('ul.tree', li).each(function() {
$(this).show();
});
$('span.clickon', ul).html('+');
$('span.clickon', ul).attr("class", "clickoff")
setclickoff();
});
}
$(document).ready(function() {
$('li.tree:has(li.tree)').prepend('<span class="clickoff">+</span> ');
setclickoff();
});
The list starts out fully expanded with a "+" next to each item that can be folded, which changes to a "-" after the folding is done. If a "-" is clicked, that item and all its children are expanded.
Thanks for any insight.