Is it possible to use jQuery .on and hover?
Asked Answered
S

11

377

I have a <ul> that is populated with javascript after the initial page load. I'm currently using .bind with mouseover and mouseout.

The project just updated to jQuery 1.7 so I have the option to use .on, but I can't seem to get it to work with hover. Is it possible to use .on with hover?

EDIT: The elements I'm binding to are loaded with javascript after the document loads. That's why I'm using on and not just hover.

Sematic answered 22/3, 2012 at 17:9 Comment(1)
From a comment below - hover event support in On() was deprecated in jQuery 1.8, and removed in jQuery 1.9. Try with a combination of mouseenter and mouseleave, as suggested by calebthebrewer.Jermaine
S
799

(Look at the last edit in this answer if you need to use .on() with elements populated with JavaScript)

Use this for elements that are not populated using JavaScript:

$(".selector").on("mouseover", function () {
    //stuff to do on mouseover
});

.hover() has its own handler: http://api.jquery.com/hover/

If you want to do multiple things, chain them in the .on() handler like so:

$(".selector").on({
    mouseenter: function () {
        //stuff to do on mouse enter
    },
    mouseleave: function () {
        //stuff to do on mouse leave
    }
});

According to the answers provided below you can use hover with .on(), but:

Although strongly discouraged for new code, you may see the pseudo-event-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.

Also, there are no performance advantages to using it and it's more bulky than just using mouseenter or mouseleave. The answer I provided requires less code and is the proper way to achieve something like this.

EDIT

It's been a while since this question was answered and it seems to have gained some traction. The above code still stands, but I did want to add something to my original answer.

While I prefer using mouseenter and mouseleave (helps me understand whats going on in the code) with .on() it is just the same as writing the following with hover()

$(".selector").hover(function () {
    //stuff to do on mouse enter
}, 
function () {
    //stuff to do on mouse leave
});

Since the original question did ask how they could properly use on() with hover(), I thought I would correct the usage of on() and didn't find it necessary to add the hover() code at the time.

EDIT DECEMBER 11, 2012

Some new answers provided below detail how .on() should work if the div in question is populated using JavaScript. For example, let's say you populate a div using jQuery's .load() event, like so:

(function ($) {
    //append div to document body
    $('<div class="selector">Test</div>').appendTo(document.body);
}(jQuery));

The above code for .on() would not stand. Instead, you should modify your code slightly, like this:

$(document).on({
    mouseenter: function () {
        //stuff to do on mouse enter
    },
    mouseleave: function () {
        //stuff to do on mouse leave
    }
}, ".selector"); //pass the element as an argument to .on

This code will work for an element populated with JavaScript after a .load() event has happened. Just change your argument to the appropriate selector.

EDIT JAN 2023

I know this is an older one but I thought id share this as it confused me a little bit, was going around in circles. But I applied the domsubtreemodifer logic that you have to target the wrapper.

Im unsure if jquery has changed over time but, You also have to include the container now that you are adding the target to.

So for example:

Your dom looks like this:

<div class="taggable">
</div>

Your adding a div like so in jquery

$('.taggable').append('<div class="close"><div>');

Your DOM will end up looking like this.

<div class="taggable">
   <div class="close"></div>
</div>

So in order for you mouse event to work you need to target the container AS well as the element you have added

$(document).on({
    mouseenter: function () {
    },
    mouseleave: function () {
    }
}, ".taggable .close"); 

$(function () {
  $('.taggable').append('<div class="close">testme<div>');
});


    $(document).on({
        mouseenter: function () {
        console.log('mouseenter');
        },
        mouseleave: function () {
        console.log('mouseleave');
        }
    }, ".taggable .close"); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="taggable">
</div>
Specialist answered 22/3, 2012 at 17:10 Comment(9)
While you're right about .hover() having its own handler, the OP's question was "Is it possible to use .on with hover?" @JonMcIntosh's answer and jsFiddle demonstrates yes.Mebane
Sure, it's possible.. But there is no need to use it with .on() when just using .hover() by itself will produce the same results.Specialist
@Scott, please note that JonMcIntosh's answer does not answer my question because he's only using half of the hover functionality.Sematic
@Toast this is the answer you are looking for.. The mouseenter and mouseleave function gives you power to do different things while using .on()Specialist
hover removed as of 1.9+ version of jQueryCablegram
@MarkSchultheiss Still important info for people working with versions of jQuery 1.9 or earlier.Specialist
@SethenMaleno - exactly, and your .on() solution works with either removing the pseudo hover event and using the real ones. I like the first one you illustrated with mouseenter/mouseleave +1 for thatCablegram
@SethenMaleno Thanks for the last bit with the .on() method to use it with populated DOM. Was using 2 .on() calls instaed of 1 cleanBiolysis
Actually, the only reason I came here, was to see if I use .hover() can I use .off() to remove it. This seems like the only reason to bother, otherwise I would use .hover() without question. It seems I need to use unbind() in combination with .hover() because off() only removes events bound with on()Emplacement
R
104

None of these solutions worked for me when mousing over/out of objects created after the document has loaded as the question requests. I know this question is old but I have a solution for those still looking:

$("#container").on('mouseenter', '.selector', function() {
    //do something
});
$("#container").on('mouseleave', '.selector', function() {
    //do something
});

This will bind the functions to the selector so that objects with this selector made after the document is ready will still be able to call it.

Retsina answered 24/9, 2012 at 19:0 Comment(6)
This one has the proper solution: #8608645Bumble
This is how I got it working too, I found the accepted answer putting the selector before the .on didn't work following a .load() event but this does.C
@calebthebrewer Edited my answer, it now takes into account elements populated with JavaScript.Specialist
Using mouseover and mouseout events here will cause the code to continually fire as the user moves the mouse around inside the element. I think mouseenter and mouseleave are more appropriate since it'll only fire once upon entry.Humdrum
I tried replacing my hover events with the jquery supplied here, but it led to undesirable effects and so I reverted my code back to using hover. The moral of the story is sometimes hover just works better.Disadvantaged
using document as the root element is not best practice, since its performance hungry. you are monitoring document, while with load() you most of the time manipulate just a part of the website (f.ex. #content). so its better to try to narrow it down to the element, thats manipulated..Mullah
C
19

I'm not sure what the rest of your Javascript looks like, so I won't be able to tell if there is any interference. But .hover() works just fine as an event with .on().

$("#foo").on("hover", function() {
  // disco
});

If you want to be able to utilize its events, use the returned object from the event:

$("#foo").on("hover", function(e) {
  if(e.type == "mouseenter") {
    console.log("over");
  }
  else if (e.type == "mouseleave") {
    console.log("out");
  }
});

http://jsfiddle.net/hmUPP/2/

Chill answered 22/3, 2012 at 17:14 Comment(5)
How does this handle the separate functions for on/off that hover uses? Ex: $('#id').hover(function(){ //on }, function(){ //off});Sematic
To me, this isn't necessary.. You don't need to use .on() with hover when you can just as easily get rid of .on() and replace it with the .hover() function and get the same results. Isn't jQuery about writing less code??Specialist
@Toast it doesn't, see my answer below to see how to perform mouseenter and mouseleave functions with .on()Specialist
I've updated my answer to include the utilization of both event types. This works just the same as Sethen's answer but has a different flavor.Chill
hover event support in On() was deprecated in jQuery 1.8, and removed in jQuery 1.9.Labia
H
11

Just surfed in from the web and felt I could contribute. I noticed that with the above code posted by @calethebrewer can result in multiple calls over the selector and unexpected behaviour for example: -

$(document).on('mouseover', '.selector', function() {
   //do something
});
$(document).on('mouseout', '.selector', function() {
   //do something
});

This fiddle http://jsfiddle.net/TWskH/12/ illustraits my point. When animating elements such as in plugins I have found that these multiple triggers result in unintended behavior which may result in the animation or code being called more than is necessary.

My suggestion is to simply replace with mouseenter/mouseleave: -

$(document).on('mouseenter', '.selector', function() {
   //do something
});
$(document).on('mouseleave', '.selector', function() {
   //do something
});

Although this prevented multiple instances of my animation from being called, I eventually went with mouseover/mouseleave as I needed to determine when children of the parent were being hovered over.

Herminahermine answered 27/2, 2013 at 18:23 Comment(1)
This answer actually provided a working solution to adding a hover event for a document selector. +1Avocation
A
11

jQuery hover function gives mouseover and mouseout functionality.

$(selector).hover(inFunction,outFunction);

$(".item-image").hover(function () {
    // mouseover event codes...
}, function () {
    // mouseout event codes...
});

Source: http://www.w3schools.com/jquery/event_hover.asp

Astaire answered 8/3, 2016 at 9:55 Comment(2)
definitely works. you got a down vote because some people are dump! Thanks mateComte
He gets a downvote because if you need late binding, which the "on" method is about, this doesn't work.Corroboree
P
7
$("#MyTableData").on({

 mouseenter: function(){

    //stuff to do on mouse enter
    $(this).css({'color':'red'});

},
mouseleave: function () {
    //stuff to do on mouse leave
    $(this).css({'color':'blue'});

}},'tr');
Plasia answered 24/11, 2013 at 5:9 Comment(0)
M
6

You can you use .on() with hover by doing what the Additional Notes section says:

Although strongly discouraged for new code, you may see the pseudo-event-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.

That would be to do the following:

$("#foo").on("hover", function(e) {

    if (e.type === "mouseenter") { console.log("enter"); }
    else if (e.type === "mouseleave") { console.log("leave"); }

});

EDIT (note for jQuery 1.8+ users):

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.

Mebane answered 22/3, 2012 at 17:40 Comment(9)
This is just more work when it can easily be done by using mouseenter and mouseleave... I know, this doesn't answer OP's original question, but still, using hover in this way, isn't wise.Specialist
Doing it this way follows exactly how the jQuery team suggests you do it in accordance to the OP's question. However, as the jQuery team suggests, it's strongly discouraged for new code. But, it's still the correct answer to the OP's question.Mebane
@Scott - you were faster than me :-). @Specialist - both ways will work, but the asker requested the functionality with .hover().Chill
Understandably so, but still, I think OP was looking for a solution for a mouseenter and mouseleave rather than just making it work with hover. If there is no real reason to use hover for performance reasons, why use it when it's strongly discouraged for new code?Specialist
@Specialist - His question stated what he was using (mousenter and mouseleave) and then asked a totally different question with regards to the new jQuery version's .on() and hover. Your answer being accepted doesn't do justice to the question asked is all I'm saying. I agree with the fact that I would personally do it your way, but the answer to the question / title of this post is what I posted.Mebane
Actually, he said he was using mouseover and mouseout which can be used as there own functions. He said nothing about mouseenter or mouseleaveSpecialist
@Specialist - You are right, I misspoke. =) Still, I hold my stance.Mebane
@Scott Totally, I understand.Specialist
hover event support in On() was deprecated in jQuery 1.8, and removed in jQuery 1.9.Labia
I
5

You can provide one or multiple event types separated by a space.

So hover equals mouseenter mouseleave.

This is my sugession:

$("#foo").on("mouseenter mouseleave", function() {
    // do some stuff
});
Inessential answered 15/5, 2013 at 14:20 Comment(1)
I like jQ's decision to depreciate this parameter. Prior version 1.8, using to hover as a namespace didn't coincide with the DOM event, hover, no relation.Epileptic
C
1

If you need it to have as a condition in an other event, I solved it this way:

$('.classname').hover(
     function(){$(this).data('hover',true);},
     function(){$(this).data('hover',false);}
);

Then in another event, you can easily use it:

 if ($(this).data('hover')){
      //...
 }

(I see some using is(':hover') to solve this. But this is not (yet) a valid jQuery selector and does not work in all compatible browsers)

Chalmer answered 19/2, 2014 at 13:27 Comment(0)
S
0

I know this is an older one but I thought id share this as it confused me a little bit, was going around in circles. But I applied the domsubtreemodifer logic that you have to target the wrapper.

The accepted answer states that you target the selector, however I found this wouldn't work for me. You also have to include the container that you are adding the target to.

So for example:

Your dom looks like this:

<div class="taggable">
</div>

Your adding a div like so in jquery

$('.taggable').append('<div class="close"><div>');

Your DOM will end up looking like this.

<div class="taggable">
   <div class="close"></div>
</div>

So in order for you mouse event to work you need to target the container AS well as the element you have added

$(document).on({
    mouseenter: function () {
    },
    mouseleave: function () {
    }
}, ".taggable .close"); 

$(function () {
  $('.taggable').append('<div class="close">testme<div>');
});


    $(document).on({
        mouseenter: function () {
        console.log('mouseenter');
        },
        mouseleave: function () {
        console.log('mouseleave');
        }
    }, ".taggable .close"); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="taggable">
</div>
Spohr answered 5/1 at 12:44 Comment(0)
P
-2

The jQuery plugin hoverIntent http://cherne.net/brian/resources/jquery.hoverIntent.html goes much further than the naive approaches listed here. While they certainly work, they might not necessarily behave how users expect.

The strongest reason to use hoverIntent is the timeout feature. It allows you to do things like prevent a menu from closing because a user drags their mouse slightly too far to the right or left before they click the item they want. It also provides capabilities for not activating hover events in a barrage and waits for focused hovering.

Usage example:

var config = {    
 sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
 interval: 200, // number = milliseconds for onMouseOver polling interval    
 over: makeTall, // function = onMouseOver callback (REQUIRED)    
 timeout: 500, // number = milliseconds delay before onMouseOut    
 out: makeShort // function = onMouseOut callback (REQUIRED)
};
$("#demo3 li").hoverIntent( config )

Further explaination of this can be found on https://mcmap.net/q/88280/-how-to-tell-hover-to-wait

Pilaf answered 6/8, 2014 at 21:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.