6/10/2009 3:10:42 PM
I've been using a lot of jQuery lately in a new project and am falling in love with it! It is a wonder why I have never used it before but am glad I was kind of forced to learn it ;)
As with anything new there is a bit of a learning curve. The application I am working on boasts a large number of tabs for different sections of the site. One of the requirements is to toggle the "active" tab via CSS class. Easy right? This was easy to do in vanilla JavaScript so it should be super-easy to do with jQuery. It is!
$('#FooItem1').removeClass('active');
$('#FooItem2').removeClass('active');
$('#FooItem3').removeClass('active');
$('#FooItem4').removeClass('active');
$('#FooItem5').removeClass('active');
That works great but there is one caveat: adding new tabs. If the requirements of the UI changed and we were to have to add a new tab (or 6 more) then we would have to not only change the view (or in this case partial view ;) ) but also the JavaScript functions dealing with these tabs. Since all of our tabs are UL with stylized LI's containing anchor tags I decided to create something like this:
function
RemoveActiveClassFromListItemControlByID(controlID) {
$("#" + controlID).children().each(function() {
$(this).children("a").removeClass("active");});
}
Now this isn't that generic since I have the "a" and "active" strings hard-coded. In this case it works for us since all the tabs are the same format and all we really need is the id of the control. This little function will enumerate the children of the control (in this case all LI's and then enumerate the A children and remove the active css class. Simple. To extend this to be even more generic you could do the following:
function
RemoveClassNamesFromChildElementByControlID(controlID, childElement, className) {
$("#" + controlID).children().each(function() {
$(this).children(childElement).removeClass(className);});
}
Here's an example of how you could use the function above. Let's say that you want to enumerate all children in a OL with an id of "fooList". Each children has a span tag with a css class of BAR and you want to reset all of them when a user clicks on a hyperlink. This would be extremely simple:
<
a href="javascript:(RemoveClassNamesFromChildElementByControlID('fooList', 'span', 'BAR'));">CLICK HERE</a>
Easy. I'm really starting to love this jQuery business.
jQuery + MVC = love
JavaScript
