Johny Jaz
Johny Jaz

Reputation: 885

One .click event handler for multiple buttons

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?

Upvotes: 1

Views: 1093

Answers (1)

tymeJV
tymeJV

Reputation: 104775

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)

Upvotes: 6

Related Questions