user385729
user385729

Reputation: 1984

binding click event for dynamic element in JQuery

I have a div which is filled dynamically after calling an AJAX call by .html attribute

$("#gallery").html(imagesHtml);

insdie imagesHtml i ahve 2 buttons called "prebtn" and "nxtbtn" now I'm trying to bind these buttons with the following syntax in JQuery:

$("#gallery").bind('click', '#nxtbtn', function() {
    alert('next');
});

and

$("#gallery").bind('click', '#prebtn', function() {
    alert('previous');
});

but whener I click on one of the buttons both events get triggered and it shows allert for "next" and "previous"; howevr I have click just one of the buttons!

Please let me know if you need more clarification.

Thanks

Upvotes: 1

Views: 144

Answers (3)

Adesh M
Adesh M

Reputation: 444

you should use on instead of using bind to get it worked on dynamically created elements. Whereas e.preventDefault() will prevent default action trigger of respective event.

$("#gallery").on('click', '#nxtbtn', function(e) {
    e.preventDefault();
    alert('next');
});

and

$("#gallery").on('click', '#prebtn', function(e) {
    e.preventDefault();
    alert('previous');
});

Upvotes: -1

David
David

Reputation: 218798

I think you meant to use .on() instead:

$("#gallery").on('click', '#nxtbtn', function() {
    alert('next');
});
$("#gallery").on('click', '#prebtn', function() {
    alert('previous');
});

The bind() function will bind to the element in the initial selector, in this case #gallery. So you're binding both functions to that event. Technically that's also what .on() does, but it uses the second argument as a filter for the element which fired the event. I don't think .bind() does that, I think that second argument is just data which your event handler functions ignore.

Upvotes: 0

lonesomeday
lonesomeday

Reputation: 237817

You're confusing the bind and on methods. They look similar, but bind has less functionality: it does not support event delegation. The second argument is not the selector for the delegated events, but a data argument.

This will work:

$("#gallery").on('click', '#nxtbtn', function() {

Upvotes: 3

Related Questions