Adam
Adam

Reputation: 29079

jQuery: Keep hovering despite browser proposal from input element

I have a navigation given by an nested ul list like this

<ul id='mainNav'>
 <li> Some Stuff!
    <ul>
     <li>Page 1</li>
     <li>Page 2</li>
    </ul>
 </li>
 <li> Hover here to login! 
   <ul >
    <li>
     <div class='login'>
      <p>Login</p>
      <input type='password'>
      <button>Okay</button>
    </div>
   </li>
  </ul>
</ul>

and I use jQuery to show the menu on hover

$('ul#mainNav > li').hover(function() {
    $(this).addClass("showMenu");
  },
  function(){
    $(this).removeClass("showMenu");
  }
);

This works fine, except for the input box for the login. In the moment where one moves the mouse pointer from the input box to a browser proposal entry, jQuery thinks that one left the li element and removes the class showMenu so that the submenu disappears.

So when I hover over the li element the login form opens enter image description here

And as soon as I hover over the browser proposal the li element dissapears except for the browser proposal

enter image description here

I also created a jFiddle.

How can I tell jQuery to keep hovering if I move over the browser proposal from the input element?

Upvotes: 0

Views: 81

Answers (1)

XYZ
XYZ

Reputation: 4480

As a solution You can remove the class .showMenu if event.target is not input Also blur the input when the dropdown becomes hidden

$('ul#mainNav > li').hover(function(e) {
    $(this).addClass("showMenu");
  },
  function(e) {
    if (!$(e.target).is('input')) {
      $(this).removeClass("showMenu");
      $('input').blur();
    }
  });
#mainNav>li {
  border: 3px solid #08C;
  background-color: #FFF;
  display: inline-block;
}

#mainNav li {
  margin: 0;
  padding: 0;
}

#mainNav,
#mainNav ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

#mainNav li>ul {
  position: absolute;
  display: none;
  z-index: 1;
  min-width: 200px;
  padding: 0px;
  margin: 0px;
  text-align: left;
  background-color: #FFF;
  box-sizing: border-box;
}

#mainNav li.showMenu>ul {
  display: block
}

.login {
  border: 3px solid #08C;
  padding: 20px;
  margin: 0
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method>

  <ul id='mainNav'>
    <li> Hover here to login!

      <ul>
        <li>
          <div class='login'>
            <p>Login</p>
            <input type='password'>
            <button>
   Okay
   </button>
          </div>

        </li>
      </ul>
  </ul>
</form>

https://jsfiddle.net/dzt87zbk/

Upvotes: 1

Related Questions