jQuery click not working for dynamically created items [duplicate]

Do this:

 $( '#wrapper' ).on( 'click', 'a', function () { ... })

 $( 'body'     ).on( 'click', '.your_dynamic_elem_css_selector', function () { ... })  # use body as wrapper static elem

where #wrapper is a static element in which you add the dynamic links.

So, you have a wrapper which is hard-coded into the HTML source code:

<div id="wrapper"></div>

and you fill it with dynamic content. The idea is to delegate the events to that wrapper, instead of binding handlers directly on the dynamic elements.


Btw, I recommend Backbone.js – it gives structure to this process:

var YourThing = Backbone.View.extend({

    // the static wrapper (the root for event delegation)
    el: $( '#wrapper' ),

    // event bindings are defined here 
    events: {
        'click a': 'anchorClicked'
    },

    // your DOM event handlers
    anchorClicked: function () {
        // handle click event 
    }

});

new YourThing; // initializing your thing

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)