Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding Jquery Events On Elements Generated Through Other Events

Tags:

html

jquery

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.

like image 987
irfanmcsd Avatar asked Mar 12 '12 18:03

irfanmcsd


2 Answers

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.

like image 83
adeneo Avatar answered Sep 29 '22 05:09

adeneo


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.

like image 38
James Montagne Avatar answered Sep 29 '22 05:09

James Montagne