Catching  dynamically generated <a href> callbacks - How to catch them?

Massimo Scola
Massimo Scola used Ask the Experts™
I have a jQuery Mobile listview (Cordova) which I populate like this:

       * @description populates the listview with all the clients
      this.populateListviewClients = function() {
        var markupHTML = [];
        for (x = 0; x < app.allClients.length; x++) {
          //create markup
          var markup = '<li><a href="#" class="modalCustomer" id="' + app.allClients[x].id + '">' + app.allClients[x].name + '</a></li>';



Open in new window

and the HTML is this:

            <form class="ui-filterable">
                <input id="filterable-input" data-type="search" placeholder="Search clients...">
              <div data-theme="b" data-content-theme="a"></div>
              <ul id="listviewClients" data-role="listview" data-filter="true" data-inset="true"

Open in new window

Everything loads nicely, but I cannot get the callback to work - even though I assigned each <a href> a generic class name.
I would like to get the callback because I would like to know which link the user clicked.

This is the callback:

  // Update DOM on a Received Event
  receivedEvent: function (id) {
    $("#allWidgets").on("click", function (e) {
      $(':mobile-pagecontainer').pagecontainer('change', '#addItems', {
        transition: "slidefade"

    $(".modalCustomer").on('click', function(e) {

Open in new window

I checked with my debugger.. the browser does not enter the <a href> callback.

What is missing in my code - or my logic?


Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2017
Distinguished Expert 2018

to attach an event handler to a dynamically created element you need to bind to a static parent element and specify the elements you are interested in. To do this

$('#listviewClients').on('click', '.modalCustomer', function() {
   // This code will now fire on any dynamically created element with the class modalCustomer

Open in new window

Why does it work like this.
When code that binds events runs it can only bind to elements that actually exist. To bind to elements created after the binding runs we bind to a parent (static) element - in this case listviewClients and then tell jQuery to look at the to see if it matches the selector (in this case) .modalCustomer. In this way we can listen for events bound to elements that are created after the binding code runs.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial