Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why hover does not work in delegated event handlers?

I am adding some elements dynamically and assigning a hover property to it in delegated event handlers for which I used below code and it did not work.

$(document).on("hover", ".sec_close_fast", function() {
  $(this).parent('div').parent('div').css("border", "3px solid #000000");
});

Then I used mouseover and it worked:

$(document).on("mouseover", ".sec_close_fast", function() {
  $(this).parent('div').parent('div').css("border", "3px solid #000000");
});

I would like to know why hover does not work, yet mouseover does.

like image 627
Amar Singh Avatar asked Jan 25 '16 11:01

Amar Singh


People also ask

What is event bubbling in js or how does event delegate work in js?

When an event is triggered on an element, for example a mouse click on a button, the same event is also triggered on all of that element's ancestors. This process is known as event bubbling; the event bubbles up from the originating element to the top of the DOM tree.

How does event work with delegate?

Event Delegation is basically a pattern to handle events efficiently. Instead of adding an event listener to each and every similar element, we can add an event listener to a parent element and call an event on a particular target using the . target property of the event object.

What is Delegation event handler?

Event delegation refers to the process of using event propagation (bubbling) to handle events at a higher level in the DOM than the element on which the event originated. It allows us to attach a single event listener for elements that exist now or in the future. Inside the Event Handling Function.

How to delegate function jquery?

The delegate() method attaches one or more event handlers for specified elements that are children of selected elements, and specifies a function to run when the events occur. Event handlers attached using the delegate() method will work for both current and FUTURE elements (like a new element created by a script).


Video Answer


1 Answers

The function / event .hover is not actually an event, but just a shorthand for mouseenter and mouseleave. From the docs:

The .hover() method binds handlers for both mouseenter and mouseleave events. You can use it to simply apply behavior to an element during the time the mouse is within the element.

So you cannot use it to "delegate" events.

Solution

As you have already mentioned and as it is mentioned in the docs, you can use:

$(static_parent).on("mouseenter mouseleave", element, function (e) {
  if (e.type == "mouseenter") {
    // check if it is mouseenter, do something
  } else {
    // if not, mouseleave, do something
  }
});
like image 92
Praveen Kumar Purushothaman Avatar answered Nov 14 '22 23:11

Praveen Kumar Purushothaman