jquery - add a class to parent items only in menu -


i working on menu want add class parent menu items through jquery. code wrote working fine if menu item dont have child elements(drop down menu). changes should make add class parent items on hover.

here html

<nav id="main-menu" style="display: block;">   <ul id="menu-nav_menu" class="nav sf-js-enabled">     <li class="menu-item cat-item">       <a href="http://localhost/carp/?page_id=45" class="sf-with-ul">         <span class="main_text">about carp</span>       </a>       <ul class="sub-menu" style="display: none; visibility: hidden;">         <li id="menu-item-41" class="menu-item">           <a href="http://localhost/carp/?page_id=40">vision</a>         </li>       </ul>     </li>     <li class="menu-item">      <a href="http://localhost/carp/?page_id=48" class="sf-with-ul">        <span class="main_text">our work</span>      </a>      <ul class="sub-menu" style="display: none; visibility: hidden;">       <li class="menu-item">         <a href="http://localhost/carp/?page_id=50">how to</a>       </li>     </ul>   </li>   <li class="menu-item">    <a href="http://localhost/carp/?page_id=79">      <span class="main_text">gallery</span></a>    </li>    <li class="menu-item">     <a href="http://localhost/carp/?page_id=81">       <span class="main_text">contact us</span></a>     </li>   </ul> </nav> 

here jquery

$(document).ready(function(){      //to change background image of previous closest menu item background     $("#main-menu ul#menu-nav_menu li a").hover(function(e) {     e.preventdefault();     var = $("#main-menu ul li span").index($(this).parent() );     $('#main-menu li span').eq(i-1).addclass('mybg');     $("#main-menu ul li a").mouseout(function() {         $('#main-menu li span').eq(i-1).removeclass('mybg');     });  }); 

i assume want highlight main menu item when hover event occurs on or children. simplest way using css:

#menu-nav_menu > li:hover > { background-color: #ff0000; } 

css fiddle


since want using jquery:

jquery

$(function () {     $('#menu-nav_menu > li').hover(function() {         $(this).children('a').toggleclass('mybg');     }); }); 

css

.mybg { background-color: #ff0000; } 

jquery fiddle


your structure hover event incorrect, please refer jquery api docs proper usage.

here's css selectors spec reference.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -