I'm ploughing ahead in my attempts to learn Mootools (damn, I miss Consider Open's 30 days tutorials) and I'm trying to build a simple class switching script. I've found one on this very site that does the trick, but ideally I'd like to be able to remove all instances of .active from the li elements, if you click on the currently active element.
I've created a JSFiddle if anyone fancies taking a look at the problem.
I did take a look at the documentation on the mootools site, but I'm afraid I still couldn't get a handle on which section would help me with this. I am keen to learn how to do this stuff myself, so I'd be greatful for not just the solution, but a pointer to the parts of the mootools documentation I should have been looking at to crack this. Thanks.
aside from performance, your code is fine. by performance, I mean - it should not have to go to the dom on every click to get the list of elements or the current active one to do what it needs to do - all that can be cached. your code will run against any .active in a collection, which initially will have .length of 0 so on first click nothing will happen. the performance issue is having to select all elements again and ones with .active, then running a .each on them for the single member that can have it.
you could do something like this instead:
http://jsfiddle.net/dimitar/m66Ju/2/
(function() {
var ul = document.getElement("ul.examples"), lis = ul.getElements("li"), active;
lis.addClass('transition');
lis.each(function(item){
item.addEvent('click',function(event){
if (active) {
// there is one, remove it.
active.removeClass('active');
}
if (active == this) {
// is the active one already open?
active = false;
return;
}
// make a new active.
active = this.addClass('active');
});
});
})();
this will be most performant and will work with an initial active li as well.
there is no manual on how to structure your code for performance and reuse, but there are a few talks that may help, like Aaron Newton's Programming to Patterns (with mootools) etc. Rule of thumb is, don't do premature optimisation but code so the slowest supported browser (usually IE6 or 7) works as fast as possible. click events afford some leeway but mouseover ones can be expensive.