My first jQuery plugin: Big Ass Menu
I am not going to get into a tutorial on how to write a jQuery plugin. There are tons of tutorials out there so I will leave that explanation to the pros. Instead I will walk you through the process of building my plugin. This is the first take so please be nice! I will also come back in future posts and correct some of the mistakes made here. The first thing we need is the core code for our plugin. With the code above we can call our new plugin using the following code.
Before we get into any more code I think its time to look at our markup. It is important to note that a plugin like this really needs 3 things to make it work well. We need to have the markup for the component (HTML), the look and feel (css) and the glue to put it all together (JavaScript). With that this is the markup we are going to work with. Our sub menus will be divs right under our main menu items.
Now that we have the core of plugin ready we need to start writing some code. First we are going to create a reference to the jquery object. Using that reference we can use that as the basis of our selector. This will indeed improve performance because we don't need to go searching the entire DOM now. In our example from above we are now strictly working with the menu node. With the code above we now have an array of menu items (menuItems) to work with. What we want to do is iterate over each of those items and do some work. Here we are going to find the id of the main menu item so we have an object to create a sub menu for. When we have that main navigation item we can look to the next node in the dom which should be our "div".
Next we are going to hide all of the sub menus and add a class to them called submenu. Later on we will make these configurable options but lets just run with this for now. With our id we can now listen for a hover event. When the user hovers over the menu item we want to fade in the sub menu and change the class of the menu item so the user knows they are "activating" a menu. When we roll off the menu item we are going to do just the opposite. This works except when we roll of the main navigation item the sub menu disappears. We can fix that by adding a hover event for the sub menu as well. When the user rolls of the main navigation item they will move onto our sub menu.
So that is my first attempt at a plugin. Like I said before, there are probably better ones out there but this is a great learning experience for me so I am running with it. I will make this code available after the next couple of posts. I also want to get some credit where it is due. The reason I was able to write this plugin is because of the jDiv Skyrocket labs plugin. This is the code that flipped on the light switch for me so thanks to them for the great resource.
