ToggleClass in event delegation not working

There is a thumb-up button on each message bubble of the chatbot. As there are multiple bubbles on each page, both the text bubble and the thumb-up button are indexed. I am attempting to delegate the event from a higher level of the DOM, but the toggleClass doesn’t work properly here. The button switched to thumb-up-black on the first click but it freezes on the second click. I wonder why

let rating_dict = { "ratingUp": {}};

$(document).on("click", ".thumbup", function() {
    const buttonid = $(this).data("index");
    
    $(this).toggleClass("thumbup thumb-up-black");

    rating_dict.ratingUp[buttonid] = !rating_dict.ratingUp[buttonid];


});
 <div class="rating-img">
    <button type="submit" class="thumbup" data-index="${message_index}""></button>
    <button type="submit" class="thumbDown" data-index="${message_index}"></button>
    </div>

>Solution :

The issue here is that you’re trying to toggle between two classes, but you’re using the same class to select the element. When you click the button for the first time, the class "thumbup" is removed and "thumb-up-black" is added. So, when you try to click it again, there’s no element with the class "thumbup" to select and the function doesn’t get triggered.

You can solve this by using a common class for selection and separate classes for toggling. Here’s how you can do it:

let rating_dict = { "ratingUp": {}};

$(document).on("click", ".thumb", function() {
    const buttonid = $(this).data("index");
    
    $(this).toggleClass("thumbup thumb-up-black");

    rating_dict.ratingUp[buttonid] = !rating_dict.ratingUp[buttonid];
});

And your HTML:

<div class="rating-img">
    <button type="submit" class="thumb thumbup" data-index="${message_index}"></button>
    <button type="submit" class="thumb thumbDown" data-index="${message_index}"></button>
</div>

In this way, the "thumb" class is used to select the element and the "thumbup" and "thumb-up-black" classes are toggled on click.

Leave a Reply