irfanmcsd
irfanmcsd

Reputation: 6561

Binding Jquery Events On Elements Generated Through Other Events

I am facing problem on binding jquery event on items created through another action e.g when load more link clicked

e.g there are list of elements
<div class="itm" id="c_1"></div>
<div class="itm" id="c_2"></div>
....

When click on load more link, it will generate more elements e.g

<div class="itm" id="c_11"></div>
<div class="itm" id="c_12"></div>
...

At page load time, i am using the following jquery script to bind mouse enter and leave event.

$('.itm').on({
   mouseenter: function (e) {
      alert('mouse enter');
   },
   mouseleave: function (e) {
     alert('mouse leave');
   }          
});    

This will successfully apply event on elements c_1, c_2 but when load more link call, it will generate more elements. for this i unbind hover events and bind it again once new elements created under function called when load more link clicked.

$(".cmtldmore").on('click', function (e) {
     // Ajax process to load more elements in tray.
     // Unbind hover event
     $('.itm').off();
     // Bind it again
     $('.itm').on({
     mouseenter: function (e) {
           alert('mouse enter');
     },
     mouseleave: function (e) {
           alert('mouse leave');    
            }
        });
    });

Both already and load more elements display properly on page, But still hover events properly call on already create elements, but not on elements created by "load more" event.

Can any one help me properly attach event on elements created dynamically through calling other jquery events or functions.

Upvotes: 5

Views: 2992

Answers (2)

James Montagne
James Montagne

Reputation: 78630

Have a look at the "Direct and delegated events" section of the on documentation:

http://api.jquery.com/on/

You can use event delegation to deal with this problem.

$('#itmWrapper').on({
   mouseenter: function (e) {
      alert('mouse enter');
   },
   mouseleave: function (e) {
     alert('mouse leave');
   }          
}, '.itm');  

This will bind the event to a wrapper element (made up the id itmWrapper, this can be body if there is no common parent) and apply to all elements matching the selector within that wrapper no matter when they are added.

Upvotes: 3

adeneo
adeneo

Reputation: 318182

On dynamic content you will need to delegate, something like this:

$(document).on({
   mouseenter: function (e) {
      alert('mouse enter');
   },
   mouseleave: function (e) {
     alert('mouse leave');
   }          
}, '.itm'); 

You should replace document with the closest parent that is not inserted with Ajax.

Upvotes: 7

Related Questions