1

The below code works -

$("#x").hover(function() {
alert("hovered");
});

But the below code does not. Please explain why?

$("#x").on("hover", function() {
alert("hovered");
});

Note - #x is a button element. and the above code works for "click" event

2
  • You are using deprecated liabrary of JQuery Commented Oct 18, 2014 at 5:40
  • what's the version of jQuery you are using ? Commented Oct 18, 2014 at 5:41

4 Answers 4

3

From jQuery .on()'s documentation:

Deprecated in jQuery 1.8, removed in 1.9: The name "hover" used as a shorthand for the string "mouseenter mouseleave". It attaches a single event handler for those two events, and the handler must examine event.type to determine whether the event is mouseenter or mouseleave. Do not confuse the "hover" pseudo-event-name with the .hover() method, which accepts one or two functions.

You could pass an object to the on method:

$("#x").on({
   mouseenter: function() {
     // ...
   },
   mouseleave: function() {
     // ...
   }
});

And if you want to delegate the events:

$('#aStaticParentOfX').on({
   mouseenter: function() {
     // ...
   },
   mouseleave: function() {
     // ...
   }
 }, "#x");
Sign up to request clarification or add additional context in comments.

Comments

0

Even the .live() has depricated from jQuery 1.9 if your version is below 1.9 you can use

$("#x").live("hover", function() {
    alert("hovered");
});

Comments

0

First: jQuery hover need 2 functions as arguments More here: http://api.jquery.com/hover/

$('#x').hover(
    function() {
        // your 'mouseenter' event handle
    }, function() {
        // your 'mouseleave' event handle
});

Second: you can simply use CSS hover pseudo-class if your code operate on the same element (#x)

#x:hover {
    // this will be added to #x when 'mouseenter', and remove when 'mouseleave'
    background-color: red;
}

Comments

0

try this..

$("#x").on("mouseover", function () {
     //wrire your code here
});

if you populated elements through javascript,use the following. It is replacement for deprecated jQuery.live.

$("body").on("mouseover","#x", function () {
     //wrire your code here
});

see this js fiddle http://jsfiddle.net/3aq48p5m/3/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.