eMTH
eMTH

Reputation: 83

How to keep submenu div hovered (visible) after mouseout?

I have a problem in getting this done. I have a submenu container (.subOptions) that becomes visible (display:block) when hover over a < li > tag.

The problem: now when mouse out of Button or div(.subOptions) the div becomes hidden.

I need somehow on page load, the first Button1 and its submenu div to be visible and while visible keep it like this when mouse out of div (and change only when hovering over the other buttons).

    <ul class="clearfix submenu">
        <li>
            <a>Button1</a>
            <div class="subOptions">
                Button 1 Content
            </div>
       </li>
       <li>
            <a>Button2</a>
            <div class="subOptions">
                Button 2 Content
            </div>
       </li>
       <li>
            <a>Button3</a>
            <div class="subOptions">
               Button 3 Content
            </div>
      </li>                                 
      <li>
            <a>Button4</a>
            <div class="subOptions">    
               Button 4 Content
            </div>
     </li>
 <ul>

Any working solution will be highly appreciated. I hope I explained clear enough.

Here is the example: jsFiddle

Upvotes: 1

Views: 754

Answers (2)

jbarnett
jbarnett

Reputation: 984

You need to check the state of the hover and only change it when a different button is selected.

(function($) {

var activeSubmenuIndex;
$('.submenu li').on('mouseenter',
    function () {
        //return if it's the same button being hovered
        if ($(this).index() === activeSubmenuIndex) {
            return;
        }
        //remove classes from other buttons, put on new active one
        $('.submenu li').removeClass('submenuHover');
        $('.submenu li a').removeClass('aHover');
        //add class for li element
        $(this).addClass('submenuHover'); 
        $(this).find('a').addClass('aHover')
    });
 })(jQuery);

I also changed two of your hover CSS classes to just regular classes that get added by the JS. Here is a working fiddle. http://jsfiddle.net/arbt0896/2/

Upvotes: 1

superUntitled
superUntitled

Reputation: 22527

You can get mostly there with css:

ul.submenu li:first-child { background:#fff; }
ul.submenu:hover li:first-child { background:#efefc8; }
ul.submenu:hover li:hover:first-child { background:#fff; }

http://jsfiddle.net/arbt0896/1/

Upvotes: 0

Related Questions