2

Is it possible to bind hover() to document with specified selector so that dynamically added content with matching attribute is assigned the JS function?

I've been looking at both this topic: JQuery .on() method with multiple event handlers to one selector and Is it possible to use jQuery .on and hover?

and I'm currently using:

$('.profile-gallery-image-container').on({
    mouseenter: function(){
        $('.delete-image', this).show();
        $('.image-options', this).show();
    },
    mouseleave: function(){
        $('.delete-image', this).hide();
        $('.image-options', this).hide();
    }
}, '.profile-gallery-image-container');

but without being able to pass the functionality to new content with matching selector.

Community
  • 1
  • 1
user1683645
  • 1,467
  • 1
  • 20
  • 26

1 Answers1

8

In delegated events approach you should bind events to one parent element of .profile-gallery-image-container. One possible solution is to bind it to <body> (or document) element:

$('body').on({
    mouseenter: function(){
        $('.delete-image', this).show();
        $('.image-options', this).show();
    },
    mouseleave: function(){
        $('.delete-image', this).hide();
        $('.image-options', this).hide();
    }
}, '.profile-gallery-image-container');
VisioN
  • 143,310
  • 32
  • 282
  • 281