Reputation: 1051
$(".hovertip").parent().on('hover', function() {
alert('yay');
});
I'd like to get something like the above working like .live() so that it catches dynamic changes to the DOM.
I tried something like this...
$(".hovertip").on('hover', $(this).parent(), function() {
alert('yay');
});
But it doesn't seem to work...
Note – this is a continuation of jQuery Live traversal parent() selector which addresessed .on() with .parent() but the dynamic DOM change issue isn't resolved.
Update:
Thanks for the suggestions...
I'm having trouble still getting this code to work live when performing actions on the function and have them work like .live when the DOM changes. For example... (this doesn't work when the DOM changes)...
$(".hovertip").parent().on('mouseenter', function() {
var hovertipParentHeight = $(this).outerHeight();
$(this).find(".hovertip").css("top", (hovertipParentHeight-hovertipHeight)/2 + "px");
I think the issue is if I were to implement a suggested solution, I'd still need $(this).parent() before the main selector to be a callback and it doesn't seem .parent() supports callbacks: http://api.jquery.com/parent/
For example:
$('.hovertip').on('hover', function(){
$(this).parent(function() {
var hovertipParentHeight = $(this).outerHeight();
$(this).find(".hovertip").css("top", (hovertipParentHeight-hovertipHeight)/2 + "px");
...
});
Doesn't work.
Upvotes: 0
Views: 1447
Reputation: 8849
Your mistake is that this
in the selector (2nd) parameter doesn't refer to .hovertip.
If you want to catch the event in each parent of a .hovertip element you could do it like this:
$('.hovertip').parent().on('hover', '.hovertip', function(){
alert('yay');
});
If the parents all have the same class you should use @Matt Stone's solution.
Update: I just saw your answer on the other post:
$(".hovertip").parent().on('hover', function() { alert('yay'); }); is working, unfortunately once the page refreshes through AJAX it stops working.
That's because it stops working when the element with the event handler attached (in your case the parents of .hovertip elements) gets replaced.
I suggest you give a class to all elements that should get the hover event handler (all parent elements of .hovertip). Then it's easy
Example: $('body').on('hover', '.hovertip', function(){});
Upvotes: 1
Reputation: 3890
.on() (and the older .live()) work by listening for bubbled events originated from their children. You can happily add/remove child elements, knowing the the parent will still be listening.
With that in mind, bind .on() to a parent element that will not be changed. You can go as high as binding it to document
.
$(".highest-level-container").on('hover', '.hovertip', function() {
console.log($(this).parent());
});
Upvotes: 1