Feb152011
11:08 pm
Use jQuery for EE Category Dropdown Menu
A big benefit of using jQuery is how it allows you to easily separate behavior from your content.
If you're already using the jQuery library in any of your projects, why not utilize jQuery's event handlers instead of injecting your semantic html code with html
event handlers. (e.g. <a onclick="alert('You clicked me!')">Click me</a>
I recently needed to use EE's nifty category dropdown menu, which allows a user to dynamically change a page location by selecting one of the categories listed in the menu. However, the example shown in the EE user guide uses an html event handler to handle the <select> tag's change event:
<select name="selcat"
onchange="location=document.catmenu.selcat.options[document.catmenu.selcat.selectedIndex].value;">
This works perfectly fine, but I wanted to pull the behavior out of the html code thereby making the javascript unobtrusive. To do that, I utilized jquery. Using the example from the EE user guide as is, the jQuery would look like this:
$(document).ready(function() {
$('select[name="selcat"]').change(function() {
window.location.assign($(this).find('option:selected').val());
});
});
Explanation
Here we are putting our change event handler code within the ready event handler,
which safely fires once the DOM is fully loaded. We're selecting all the <select> tags with
a name attribute of 'selcat' and binding the change event to them. Then we use the
assign method of the location object to load the value, which
is a URL, of the option selected.
And that's it. Nothing too fancy here. Just another example of combining two great undertakings—ExpressionEngine and jQuery—to make something awesome.
This article was last updated on Mon February 21, 2011 at 12:47 pm
Leave a comment