let's discuss the premise of this particular code:
<span class="menuitem">Howdy</span>
<span class="menuitem">Howdy</span>
<span class="menuitem">Howdy</span>
<span class="menuitem">Howdy</span>
<span class="menuitem">Howdy</span>
this is the corresponding CSS:
.menuitem{border-bottom: 4px solid #888888;}
.menuActive{border-bottom: 4px solid blue;}
the javascript part goes like this:
$('.menuitem').click(function(){
$('.menuitem').removeClass('menuActive');
$(this).prevAll().andSelf().addClass('menuActive');
});
here's a link to the live example on JSFiddle: http://jsfiddle.net/vE6yW/
EDIT: relevant for jQuery versions 1.8 and 1.9+.
In jQuery version 1.8, the addBack()
method was introduced whereas in version 1.9, the andSelf()
method was removed. So, for jQuery 1.8 onwards, please use the following:
$('.menuitem').click(function(){
$('.menuitem').removeClass('menuActive');
$(this).prevAll().addBack().addClass('menuActive');
});
This modification ensures the same effect as before. Additionally, addBack()
allows for adding a selector to specify which elements are included in the added selection group if needed.