.hover (...) and further ("hover" ...) behave differently

Using jQuery I'm trying to bind several functions when an element has a hang state.

I would usually use the event function .hover, but after reading some of the tutorials, I read that use is .onbetter, since you can use one event handler to monitor all the bubble events in the document.

However, I am having problems when I connect two functions together like this:

$("element").on( "hover", function() {         
    console.log("one");     
}, function() {         
    console.log("two");     
});

I expected the result to be one two (this was the case if used .hover), but instead I get two two .

Can someone explain what I'm doing wrong, or is this the expected behavior and why?

Reproduced with .hover(...): http://jsfiddle.net/gXSdG/

Reproduced with .on(hover...): http://jsfiddle.net/gXSdG/1/

+5
source share
2 answers

.on()can take only 1 function, so you need to interrogate the passed eventto check what happened. Try the following:

$("element").on("hover", function(e) {
    if (e.type == "mouseenter") {
        console.log("one");   
    }
    else { // mouseleave
        console.log("two");   
    }
});

Script example

Alternatively, you can separate the two events that make up the method hover()- mouseenterand mouseleave:

$("#element").on("mouseenter", function() {
  console.log("one");   
}).on('mouseleave', function() {
  console.log("two");   
});
#element {
  background-color: black;
  height: 100px;
  margin: 100px;
  width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="element"></div>
Run codeHide result
+29
source

, , . API- hover on , , :

hover , . , - .

on , , , , .

+2

All Articles