seahorsepip seahorsepip - 3 months ago 7
HTML Question

Correct way to target button elements inside jquery element?

I have jQuery elements

popup
and
buttons
,
buttons
is a child of
popup
.




buttons
contains
<button>
elements which I want to attach a click event to.

So I write the following code to do so:

buttons.children("button").on("click", function() {
//I'm magic
}


But sadly the content of
buttons
can be dynamically changed, buttons can be added and removed :/

So I solved that by writing:

buttons.on("click", "button", function() {
//I'm magic
}


But
buttons
itself can be added and removed from
popup
. After
buttons
is removed from and added back to
popup
above code does no longer work :/

The following code seems to solve it:

popup.on("click", "button", function() {
//I'm magic
}


But this also triggers when a
<button>
is clicked that's inside
popup
but not inside
buttons
.

How to trigger it only when a
<button>
is inside
buttons
is clicked?

Thanks for any help!

Answer

Give a class to all the buttons elements, and refer to that in the delegation.

popup.on("click", ".buttons button", function() {
    ...
});

OK, here's how you might be able to do it without adding classes:

popup.on("click", "button", function() {
    var clickedButton = this;
    buttons.each(function(i, aButton) {
        if ($.contains(aButton, clickedButton)) {
            // I'm magic
            return false; // stop looping
        }
    });
});

This uses delegation to trigger on any button in popup. Then when the code is triggered, it searches through all the buttons to see if this button is within one of them. If so, it executes the code you want, and breaks out of the loop.