1

I am creating some buttons in my jQuery mobile website dynamically. I create them like this:

$('#Gallery' + i + ' .gallery').after('<button type="button" class="loadMorePhotos">More Photos...</button>');

Then I create a simple .click event handler like this :

$(".loadMorePhotos").click(function(){
            alert("ok malaka!");
});

I was cautious enough NOT to use the id attribute to identify the buttons , as I have multiple buttons and that would mess things up. Instead I use the class attribute that as far as I understand should work.

However the alert is never executed. What could I be doing wrong here?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Johny Jaz
  • 875
  • 2
  • 13
  • 26
  • Are you sure you are binding the event handler *after* the element has been inserted? Please post a more complete example which shows the relation between those two statements. – Felix Kling Jul 03 '13 at 15:10
  • possible duplicate of [Events triggered by dynamically generated element are not captured by event handler](http://stackoverflow.com/questions/12829963/events-triggered-by-dynamically-generated-element-are-not-captured-by-event-hand) – Felix Kling Jul 03 '13 at 15:14
  • Thank you very much @Felix for your edit and for pointing out another very useful question. Cheers! – Johny Jaz Jul 03 '13 at 15:17

1 Answers1

6

Event delegation:

$(document).on("click", ".loadMorePhotos", function(){
        alert("ok malaka!");
});

Because your elements are dynamically created, you have to bind the click handler to an element that already exists at DOM ready (in this case, document)

tymeJV
  • 103,943
  • 14
  • 161
  • 157