mouseenter triggered on page load & if no other mouseenter event is triggered

耗尽温柔 提交于 2020-01-06 11:26:12


I would like to trigger a mouseenter on my menu item '#currentitem a' when my page loads. That I have done with:

  $("#currentitem a").trigger('mouseenter');

My problem is that if I mouseenter (manually) another item, the triggered (with code above) item doesn't mouseleave. Menu items overlap.

I am a newbie, I would like to achieve the following if it is possible?

  1. mouseenter '#currentitem a' on pageload.
  2. mouseleave '#currentitem a' when another item has a mouseenter triggered.
  3. When that menu item triggers mouseleave, mouseenter '#currentitem a' so the item is always triggered when nothing else is.

The menu is part of a more complex jQuery setup, and not just plain CSS so this is the best way I can see to do it. Any help would be much appreciated.

I have now created a JSFiddle to show what I am trying to do:


Here is something to try that should work

    $('#currentitem a').trigger('mouseenter');
    $('.currentitem a').on('mouseenter', function(e) {
        if ($('.currentitem a:focus').length > 0) {
            $('.currentitem a:focus').blur();

If this does not work please let me know and I will tweek it.


After looking over your edits, i might have found your problem

When you are targeting elements with jQuery, the id attribute should only be used once in your DOM. Assuming that this is true with your html, the next thing I would guess is that you are not listening for when the mouse enters a different item (for example the next li in your list). If this is true, you just need to listen for the mouseenter event on the other li elements.

Lastly if you are listening for the events but they are not working, there is another event they might work for you. The event is mouseover

Mid-edit update:

If you are talking about the menu not hiding when you mouse straight over "Our Projects" without hitting anything else, that is because the mouse never "entered" the element so it will not hide itself, the way around this is simple:

$("#mydroplinemenu > ul > li[id!='currentitem'] > a").one('mouseenter', function(e) {
   $('#currentitem a').trigger('mouseleave'); 

That selector for my event targets only link elements that are not #currentitem and will only trigger once for each link. This might me just what you are looking for! I tested it on your jsfiddle and it indeed worked.