Talha
Talha

Reputation: 19242

Click event not firing with dynamically create buttons

I have dynamically created the buttons in a div. And binding the click and other events for the buttons. But the problem is, click event fired only one for first clicked button. It happens same for the other binding events. The sample code is

 $('#divButtons input[type=button]').each(function () {
     $(this).bind('mouseover', function (e) {
         // some work
     }).bind('mouseout', function (e) {
         // some work
     }).bind('click', function (e) {
         // some work
     });
 });

It works good when bind it on document.ready() But in my case buttons created far after DOM ready.

I also want to know why it behaves like this...?

Upvotes: 0

Views: 758

Answers (1)

adeneo
adeneo

Reputation: 318182

If using jQuery 1.7+ go for on(), and there's really no need for each() :

$(document).on({
    mouseover: function(e) {
            // some work
    },
    mouseout: function(e) {
           // some work
    },
    click: function(e) {
           // some work
    }
}, '#divButtons input[type=button]');

replace document with nearest non dynamic element for delegated event handler.

Upvotes: 5

Related Questions