views:

49

answers:

1

I am just learning jQuery and I wanted to see what I could do with the function below. This function adds or removes css classes to create a pull down menu (it is in fact Stu Nicholl's well known pull down menu). But I'm not getting very far (I've been learning jQuery for approximately an hoour now, so my DOM traversal isn't quite up there yet). I am curious to see how neat and elegant it can become using jQuery, and thought I'd see what you guys could come up with. Here is the existing function:

 var getEls = document.getElementById("menu").getElementsByTagName("LI");
 var getAgn = getEls;
 for (var i=0; i<getEls.length; i++) {
 getEls[i].onclick=function() {
 for (var x=0; x<getAgn.length; x++) {
 getAgn[x].className=getAgn[x].className.replace("unclick", "");
 getAgn[x].className=getAgn[x].className.replace("click", "unclick");
 }
 if ((this.className.indexOf('unclick'))!=-1) {
 this.className=this.className.replace("unclick", "");;
 }
 else {
 this.className+=" click";
 }
 }
 }
 }

My first failure started like this:

$(document).ready(function() {
  $('#menu > li').click(function() {
     $('#menu >li > ul').toggleClass('unclick');
  });
});

That works as far as it goes, but the next bit proved tricky. So, if anyone feels like having a go, please be my guest :)

A: 

Untested, but I think this does what you want.

jQuery(function () {
    var menus = jQuery('#menu li');
    var open_menu = function open_menu() {
        var menu_to_open = jQuery(this);
        if (menu_to_open.hasClass('open')) {
            menu_to_open.removeClass('open');
        } else {
            menus.removeClass('open');
            menu_to_open.addClass('open');
        }
    };
    menus.click(open_menu);
});
David Dorward