Nuvolari
Nuvolari

Reputation: 1155

Create A JQuery Hover From Two Seperate Functions

I have the following code:

$('body').on('mouseenter', 'img[id$=_fav]', function(event) {
    $(this).parent().css("border-top-color", "#000");
});
$('body').on('mouseleave', 'img[id$=_fav]', function(event) {
    $(this).parent().css("border-top-color", "gray");
});

I am wondering how can I merge both of those into a single hover event or is this not possible using the 'live' way?

I want something like this:

$('body').on('hover', 'img[id$=_fav]', function(event) {
function(){ //mouse enter
$(this).parent().css("border-top-color", "#000");
}
function(){ //mouse leave
$(this).parent().css("border-top-color", "gray");
}
}

Upvotes: 0

Views: 69

Answers (3)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Basically you want to hook hover event on an element which was created/added dynamically into the DOM. Since we can't achieve the same syntax of hover with on, we could alternatively use the event type to divert the control flow. Technically speaking, hover will simply handle both mouseenter and mouseleave behind the screen. Try using the following code,

$(document).on("hover",'img[id$=_fav]', function(e) {
  if(e.type == "mouseenter") {
      }
  else if (e.type == "mouseleave") {
      }
});

DEMO based on 1.8 and below

Note : Please skip the above part. Just know about it for your future usage


Since hover event was removed from Jquery after 1.9, But not .hover() function. You cant use it hereafter with latest libraries. Instead try to handle by using mouseenter and mouseleave like below,

$(document).on({
    mouseenter: function () {

    },
    mouseleave: function () {

    }
}, 'img[id$=_fav]');

DEMO based on latest versions of JQuery

Upvotes: 1

Rohan Kumar
Rohan Kumar

Reputation: 40639

Don't use function() { twice for mouseenter and use , to separate mouseenter and mouseleave events like,

$('img[id$=_fav]').hover(function(event) {// use function() once for mouse enter event
   $(this).parent().css("border-top-color", "#000");
},function(){ //mouse leave, you missed a comma in your code
   $(this).parent().css("border-top-color", "gray");
});

Read hover()

Updated if you want to use hover for dynamically added elements then you have to use on() with mouseenter mouseleave events as you are using,

From jQuery.on()

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.

Upvotes: 2

undefined
undefined

Reputation: 2101

It's done exactly like you want: see the docs.

Upvotes: -2

Related Questions