1

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

1
  • 2
    .bind doesn't support the event delegation syntax the same way .on does. Commented Oct 30, 2013 at 19:02

3 Answers 3

3

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() {
Sign up to request clarification or add additional context in comments.

12 Comments

your code gave me the following error: Uncaught TypeError: Object #<Object> has no method 'on'
@Pasargad In that case you're using an ancient version of jQuery. Use a modern one.
@Pasargad: What version of jQuery are you using? .on() was introduced in 1.7, which is very old.
I knwo but lost of my stuff already dependent to the old version of JQUery; they are not compatible with the newer version :(
Use .delegate() for older jQuery versions than 1.7
|
0

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.

Comments

-1

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');
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.