While working on the user interface of the WordPress Plugin I’m building, I needed to have something akin to a drop down menu. A user clicks on a menu item, and a related list appears elsewhere on the page (in my case it’s a tool menu). To achieve this functionality I first looked at existing jQuery scripts and plugins and considered Superfish, which I was already using for the tab navigation. Using multiple instances of Superfish on the same page didn’t look as straightforward as it should be so I looked to build my own jQuery script, how hard could it be?
On my first attempt I worked with my limited jQuery knowledge and wrote a lot of code. It worked, it was logical but I knew I wasn’t being efficient. One of the most common mistakes for beginners to jQuery is to assign click handlers more generously than needed. My first attempt resulted in a lot of redundant code – I had assigned click handlers to every link in the menu.
Later I revisited my first attempt (which did work) and went about refactoring the code to get something more efficient. My secondary goal was to lose the need for Superfish on my other tab nagivation as well. My first step was to apply event delegation properly. Instead of assigning click handlers to each link in the menu, I assign a handler to the menu. There are a couple of functions to achieve that in jQuery, such as click(), bind(), live(), delegate() and on(). They all have their own merits and optimal use cases. On() seemed the most attractive to me for my interface, but since it has only recently been introduced in jQuery 1.7 I’m using delegate() in my plugin since the current WordPress ships with an older version*. I’ll show how it works for both, since the difference is minimal.
* WordPress 3.3 will come with jQuery 1.7
with delegate(): [javascript] $(“#divtoggle”).delegate(“a”,”click”, function(e) { // do stuff }); [/javascript] with on(): [javascript] $(“#divtoggle”).on(“click”, “a”, function(e) { // do stuff });
[/javascript]