I have an event handler bound to the hover event using the .hover method, which is below:
$(".nav li").hover(function () {
$(this).addClass("hover");
}, function () {
$(this).removeClass("hover");
});
It is important to note, that I require both functions within the handler to ensure synchronisation. Is it possible to rewrite the function using .delegate, as the following does not work?
$(".nav").delegate("li", "hover", function () {
$(this).addClass("hover");
}, function () {
$(this).removeClass("hover");
});
Rich
Try this approach:
This depends on
.navnot getting replaced via AJAX or otherwise though, since that’s where the event handler lives. If it is being replaced, you have to attach the delegate on a higher ancestor that’s not getting replaced.Also a minor correction,
$(".nav li").hover(function () {isn’t using the.live()method, that would be:$(".nav li").live('hover', function () {..hover()binds the event directly to the element when that code runs…any future elements wouldn’t trigger that hover code, that’s where.live()and.delegate()differ, they work on future elements via bubbling.