سؤال

I am trying to create a simple jquery menu but encounter a problem. Here is my script:

<script>
$(function(){
$('#tm-u, #tm-e, #tm-n').click(function(){
 $( '#topmenu' ).css('display', 'block');
});
$('#topmenu').mouseleave(function(){
 $(this).css('display', 'none');
});
});
</script>

My html structure is this:

<div id="login">
<a href="#tm-u">1</a>
<a href="#tm-e">1</a>
<a href="#tm-n">1</a>
</div

<div id="topmenu">
stuff
</div>

The thing is that the topmenu appears UNDER the login element (using z-index) because I want the menu to appear under it and keep the functionality of the login buttons to change content inside 'topmenu'.

However using mouseleave, whenever the cursor enters the login element the topmenu closes and I want it to stay open.

So in other words, I want the topmenu element to stay visible even when you hover on the login element that is sitting above it.

How can I do this? I tried using this code but it's not working :/

$('#login').mouseenter(function(){
if ($('#topmenu').is(':visible')) {
alert('h');
$( '#topmenu' ).css('display', 'block');
};
});
هل كانت مفيدة؟

المحلول

A good solution would be to change your markup, and wrap both elements (#login and #topmenu). Then bind the mouseleave handler to their parent.

HTML:

<div class="loginWrapper">
  <div id="login">
    <a href="#tm-u">1</a>
    <a href="#tm-e">1</a>
    <a href="#tm-n">1</a>
  </div>

  <div id="topmenu">
    stuff
  </div>
</div>

JS:

$('.loginWrapper').mouseleave(function(){
  $('#topmenu').css('display', 'none');
});

This way, your mouse will have to leave the wrapper, and all of it's children, in order to fire.

نصائح أخرى

This looks like a CSS problem.

Try this...

#topmenu:hover,
#login:hover + #topmenu {
  display: block;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top