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.
(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:
.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:According to the answers provided below you can use
hoverwith.on(), but:Also, there are no performance advantages to using it and it’s more bulky than just using
mouseenterormouseleave. 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
mouseenterandmouseleave(helps me understand whats going on in the code) with.on()it is just the same as writing the following withhover()Since the original question did ask how they could properly use
on()withhover(), I thought I would correct the usage ofon()and didn’t find it necessary to add thehover()code at the time.EDIT DECEMBER 11, 2012
Some new answers provided below detail how
.on()should work if thedivin question is populated using JavaScript. For example, let’s say you populate adivusing jQuery’s.load()event, like so:The above code for
.on()would not stand. Instead, you should modify your code slightly, like this:This code will work for an element populated with JavaScript after a
.load()event has happened. Just change your argument to the appropriate selector.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:
Your adding a div like so in jquery
Your DOM will end up looking like this.
So in order for you mouse event to work you need to target the container AS well as the element you have added