Search code examples
javascriptjqueryhtmlhoverjquery-hover

Keep CSS style of a parent element while hovering its children elements


I have created a nav with a menu were whenever you hover in a section it displays a blue line. My problem is that there's a submenu inside a section and I want that when you hover in the submenu's sections (child) the parent still displays the blue line as it were still hovered.

//Display Submenu
$('nav .submenu').hover(function() {
    $(this).children('ul').animate(
        {'height':'toggle'}, 600, 'swing'
    );
});

//Blue Line animation
$('nav ul > li a').hover(function(){
    $(this).next('.blueLine').animate(
        {'width':'100%'}, 200, 'linear')
},function(){
    $(this).next('.blueLine').animate(
        {'width':'0'}, 200, 'linear');      
});

Here's a working fiddle


Solution

  • If you keep HTML structure as in your example, then you can try this:

    $('nav ul > li a').hover(function(){
      $(this).next('.blueLine').stop().animate(
        {'width':'100%'}, 200, 'linear');
      $(this).closest('ul').prev().stop().css('width','100%');
    },function(){
      $(this).next('.blueLine').stop().animate(
        {'width':'0'}, 200, 'linear');
      $(this).closest('ul').prev().stop().animate(
        {'width':'0'}, 200, 'linear');
    });
    

    JSFiddle