1

index.html:

<html>
<head>
    <title>chapter 5</title>
    <script src="jquery.js"></script>
    <script src="app.js"></script>

</head>
<body>
    <div >
        <p>this is a paragraph</p>
    </div>
</body>
</html>

app.js:

$(function() {
    $("div").on("hover", function(event) {
        if(event.type === "mouseenter") {
            $(this).css("background", "blue");
        } 
        else {
            $(this).css("background", "red");
        }
    });
});

so according to my Jquery: when I bring mouse over to tags it should change its colour to red and when any other even inside tag except mouse enter it should change to blue. But nothing is happening?

I have tried other functions with event which works fairly well I can not understand why this one is not working do I have to do something with "css" maybe?

2
  • I'm wondering why you did not use mouseenter from the beginning. Keep in mind to not add overhead such as that in your code Commented Dec 29, 2013 at 21:58
  • I was actually trying out some examples from a book to learn jQuery interestingly the book is published in 2013 and still using "hover" which is removed. Commented Dec 29, 2013 at 22:21

1 Answer 1

3

From the jQuery's .on() method 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.

Listen to mouseenter and mouseleave events instead of the hover:

$("div").on("mouseenter mouseleave", function(event) {
   $(this).css("background", event.type === "mouseenter" ? "blue" : "red");
});

Alternatively you can pass an object to the .on() method:

$("div").on({
   mouseenter: function() {
      $(this).css("background", "blue");
   },
   mouseleave: function() {
      $(this).css("background", "red");
   }
});
Sign up to request clarification or add additional context in comments.

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.