I haven't looked at the code you linked to but I've looked at the code
you posted. It's actually pretty compact, not to much room for
chaining.

The easiest "speed up" would be to "cache" your selectors, the
"mainnav" in particular:

    var menu = $("#mainnav");

So this: $("#mainnav li.active")
becomes: $("li.active", menu).

And this :$("#mainnav li a")
becomes: $("li a", menu)

You could even cache the "li" elements, if there are no new ones added
or old ones taken away:

    var items = $("#mainnav li");

So this: $("#mainnav li.active")
becomes: items.filter(".active")

And this: $("#mainnav li a")
becomes: $("a", items)

After a few other minor changes your original code becomes:

// save LIs
var items = $("#mainnav li");

// save old active items and clear
var oldActive = items.filter(".active").removeClass("active");

// find current
var noCurrent = true;
$("a", items).each(function() {
        if( isCurrent(this, 'href') ) {
                $(this).parent().addClass("active"); // activate current
                noCurrent = false;
                return false; // to stop the "each", like a "break" in a "for" 
loop
        }
});

// re-activate old one if nothing is active
if( noCurrent )
        oldActive.addClass("active");

Slightly less "compact" but a bit faster due to the caching of selections.

Karl Rudd

On 10/10/07, malvim <[EMAIL PROTECTED]> wrote:
>
> Hi!
>
> I'm new to jQuery, and I'm experimenting with it a little. What I want
> to do is add some menu items to my Trac installation, as shortcuts to
> my most used pages and reports (I am using jQuery inside GreaseMonkey
> for that).
>
> So, the menu is structured as a div that has an id, and an unordered
> list inside of it. Each menu item is a list item.
>
> Adding the menu was pretty straightforward, but getting them to
> highlight when needed was not as easy for me. This is what I did:
>
> // save old active menu
> var oldActive = $("#mainnav li.active");
>
> // clear actives
> $("#mainnav li.active").removeClass("active");
>
> // activate current
> $("#mainnav li a").filter(function() {
>         return isCurrent(this, 'href');
> }).parent().addClass("active");
>
> // re-activate old one if nothing is active
> if($("#mainnav li.active").length == 0) {
>         oldActive.addClass("active");
> }
>
> isCurrent is a function that tests if the url passed to it is the
> current document.location.href.
>
> This is not too bad, I guess, but I'd like to learn a little bit more
> about jQuery. Is there a more jQuery-ish way to do this?
>
> The complete code is here: 
> http://marceloalvim.com/jquery/trac_menu_extension.js
>
> Thanks for the help!
>
> Cheers,
> Marcelo Alvim.
>
>

Reply via email to