[jQuery] help optimizing this code ?
Hi all
I have this piece of code that works fine, but is a bit slow (on a
page with =~ 25 container and =~ 70 buttons, it takes about 2 to 3
seconds to complete, even after I made my best to narrow down the $
(elt) set on which it is called). So I if anybody here has any idea to
improve it...
NB : jquery-1.2.3, ff2/ubuntu.
$.fn.OneOfTogglers = function(options) {
options = $.extend({}, $.fn.OneOfTogglers.defaults, options);
var containerSelector = options.togglerContainerSelector;
var buttonClass = options.buttonClass;
var buttonSelector = options.buttonElt + "." + buttonClass;
var targetClass = options.targetClass;
var targetSelector = options.targetElt + "." + targetClass;
var buttonOpen = options.buttonOpen;
var buttonClose = options.buttonClose;
var setClosedState = function() {
$("img", this).attr(buttonOpen);
};
$(containerSelector, this).each(function() {
var domchunk = this;
var $targets = $(targetSelector, domchunk).hide();
var $buttons = $(buttonSelector, domchunk);
$buttons
.each(setClosedState)
.click(function() {
var targetId = "#" +
this.id.replace(buttonClass, targetClass);
var $target = $(targetId, domchunk)
var $img = $('img',
this);
var closed = $target.css('display') ==
'none';
// are we closed yet ?
if (closed) {
// if so, close the others
$targets.not(targetId).hide();
$buttons.each(setClosedState);
// then open this one
$img.attr(buttonClose);
$target.show();
}
else {
$img.attr(buttonOpen);
$targetId.hide();
}
return false;
});
});
return this;
};
$.fn.OneOfTogglers.defaults = {
togglerContainerSelector: "ul.toglist",
buttonClass: "togbutton",
buttonElt : "a",
targetClass: "togtarget",
targetElt: "div",
buttonOpen: {
src:'images/plus.gif',
alt:'+'
},
buttonClose: {
src:'images/minus.gif',
alt:'-'
}
};
TIA...