Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading