0

I have a <ul id="list"> and <li class="item-class">. When user hovers over an <li> inside of <ul> I want to first trigger the <ul> hover and then <li> hover because in my particular situation the order is significant. However, jQuery first fires <li> hover and then the <ul> event - is there a way to revert this order?

Let's have an unordered list:

  <ul id="list">
    <li class="list-item"> Argentina </li>
    <li class="list-item"> Mexico </li>
    <li class="list-item"> Brazil </li>
  </ul>

and this jQuery code:

function bindHoverEvents() {
    $('#list').hover(() => console.log("1. List hover"),
                     () => console.log("4. List unhover"));
    $('.list-item').hover(() => console.log("2. Item hover"),
                          () => console.log("3. Item unhover."));
}

When user hovers over an <li> and then unhovers back I a want to see

"1. List hover"
"2. Item hover"
"3. Item unhover."
"4. List unhover"

in the console, however, for some reason I see this:

"2. Item hover"
"1. List hover"
"3. Item unhover."
"4. List unhover"

Here's MRE: http://jsfiddle.net/frz24w9L/

tomashauser
  • 561
  • 3
  • 16
  • It's not jquery, it's the browser that's sending the events. – freedomn-m Oct 01 '21 at 09:38
  • How do I alter that order or simulate it via different approach? – tomashauser Oct 01 '21 at 09:38
  • First of all, some background: [What is event bubbling and capturing?](https://stackoverflow.com/questions/4616694/) You would need to handle events in the capturing instead of the bubbling phase. But AFAIK jQuery does not support that, so you might need to use a different library, or a native implementation then. – CBroe Oct 01 '21 at 09:40
  • 1
    Call the `list hover` from within the `item hover` : http://jsfiddle.net/0d5gxtv6/ – freedomn-m Oct 01 '21 at 09:41
  • Alternatively only listen on list hover and use event bubbling to determine the event target element (the item) - essentially the same but on the list instead of item – freedomn-m Oct 01 '21 at 09:43
  • @freedomn-m this is technically correct but you're firing list hover everytime you move to a different item - list hover should only fire once and then when hovering between items it should not fire again if you know what I mean. – tomashauser Oct 01 '21 at 10:36
  • That's the compromise. You could check if it's the same list if you have something to do (or check that you haven't already done it, such as adding a class) – freedomn-m Oct 01 '21 at 10:39
  • I might switch a variable on item hover and then check whether it hasn't already been switched on list hover and finally unswitch it on list unhover maybe. – tomashauser Oct 01 '21 at 10:43

0 Answers0