user1032531
user1032531

Reputation: 26281

Remove hover with on()

I would like to have both a hover and remove hover event. The nodes which have this event are added dynamically, so I wish to use on(). When adding a hover event, it works great (the #second list below). For some reason when I add the off hover event, not even the add hover event will work (#first list below).

Please provide any clues. A live example is located at http://jsfiddle.net/NV7hR/

Thanks

$(document).ready(function() {
  $("#first").on("hover", "a", function(event) {
    $(this).parent().css("background-color", "yellow");
  }, function(event) {
    $(this).parent().css("background-color", "");
  });
  $("#second").on("hover", "a", function(event) {
    $(this).parent().css("background-color", "yellow");
  });
});

<body>
<ul id="first">
    <li><a href="#"/>Link</a></li>
    <li><a href="#"/>Link</a></li>
    <li><a href="#"/>Link</a></li>
</ul>
<ul id="second">
    <li><a href="#"/>Link</a></li>
    <li><a href="#"/>Link</a></li>
    <li><a href="#"/>Link</a></li>
</ul>
</body>

Upvotes: 0

Views: 304

Answers (3)

user1106925
user1106925

Reputation:

In spite of what everyone else claims, you can indeed use 'hover' with .on().

It's just that you can't pass 2 functions. You need to test the event type.

$("#first").on("hover", "a", function(e) {
    $(this).css("background-color", e.type === 'mouseenter' ? "yellow" : '');
});

DEMO: http://jsfiddle.net/HxuuS/


FYI, the reason passing 2 functions caused it to not work at all is that the first handler was interpreted as the optional data argument to on, so it was only the second handler (the mouseleave one) that was being bound.

Upvotes: 2

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

.hover as such is not an event. hover is shorthand for mouseenter and mouseleave events. Try using like below,

DEMO

$("#first").on({
    mouseenter: function() {
        $(this).parent().css("background-color", "yellow");
    },
    mouseleave: function() {
        $(this).parent().css("background-color", "");
    }
}, 'a');

Upvotes: 3

Paul Sham
Paul Sham

Reputation: 3205

Split the hover into mouseenter and mouseleave, which is what hover is shorthand for anyways.

$("#first").on("mouseenter", "a", function(event) {
   $(this).parent().css("background-color", "yellow");
}).on("mouseleave", "a", function(event) {
   $(this).parent().css("background-color", "");
});

Upvotes: 4

Related Questions