Gargoyle
Gargoyle

Reputation: 10324

Unable to toggle class via javascript

I've got a set of tr tags in a table and some of them have a class of collapsible-parent. When I click on an element in the row it calls this javascript method:

function toggle() {
    $(this).closest("tr").nextUntil(".collapsible-parent").toggleClass("open");
}

But none of the rows inbetween are having the open class added. So the HTML is something like so:

<tr class="collapsible-parent">
    <td>
        <span onclick="toggle()"><i class="fa fa-chevron-circle-right"></i></span>
    </td>
    ...
</tr>
<tr>....</tr>
<tr>....</tr>
<tr class="collapsible-parent">....</tr>

so if I trigger that method on the first tr shown, I'd want the second and third tr to have the open class added to them.

What have I done wrong?

Upvotes: 0

Views: 125

Answers (1)

Harry Theo
Harry Theo

Reputation: 784

I just now realised that you have fixed your problem, though I will keep the answer for future reference as it is a tricky bug.

The onclick event listener is not captured correctly by jQuery. I have managed to run this successfully by adding an id on the span element and then adding an .on("click") listener using jQuery.

Add an id on the span element:

<span id="btn"><i class="fa fa-chevron-circle-right"></i></span>

and add a listener using jQuery:

$("#btn").on("click", function() {
    $(this).closest("tr").nextUntil(".collapsible-parent").toggleClass("open");
});

Upvotes: 1

Related Questions