Reputation:
I'm putting together a nav bar and found a nice script to allow a li to keep in its 'hover' state while a 2nd level menu is displayed. In my last li I have a search bar and would like to remove the hover. Code:
<script type="text/javascript">
$(document).ready(function() {
$("ul#topnav li").hover(function() { //Hover over event on list item
$(this).css({ 'background' : '#7bbdc2 '}); //Add background color + image on hovered list item
$(this).find("span").show(); //Show the subnav
} ,
function() { //on hover out...
$(this).css({ 'background' : 'none'}); //Ditch the background
$(this).find("span").hide(); //Hide the subnav
});
});
</script>
Upvotes: 2
Views: 519
Reputation: 39882
You can exclude an element from the selector. Do that.
<script type="text/javascript">
$(document).ready(function() {
$("ul#topnav li").not('li:last').hover(function() { //Hover over event on list item
$(this).css({ 'background' : '#7bbdc2 '}); //Add background color + image on hovered list item
$(this).find("span").show(); //Show the subnav
} ,
function() { //on hover out...
$(this).css({ 'background' : 'none'}); //Ditch the background
$(this).find("span").hide(); //Hide the subnav
});
});
</script>
Upvotes: 2
Reputation: 20550
didn't test my suggestion. try this:
$("ul#topnav li:last-child").hover(nil);
following your existing code. your code adds the hover element to all li
elements in #topnav, so after this find the last one and remove the hover.
Note: this is not the best solution because when you add some new li
element below the search you will end up with the wrong result.
better give the search li
element its own unique identifier and remove the hover on this element:
$("ul#topnav li#search").hover(nil);
EDIT:
or even better - use the attribute not equal selector right from the beginning..
instead of:
$("ul#topnav li").hover(function() {
// ...
give your search li
the id
"search" and do this:
$('ul#topnav li[id!="search"]').hover(function() {
// ...
http://api.jquery.com/attribute-not-equal-selector/
Upvotes: 3