Skip to content
Advertisement

jquery remove class / addClass not doing anything [closed]

I use some switch in jquery to add/remove class:

I have some image i need to toggle when user click on it:

    <div class="col-6 text-right mb-3">
            <span class="hover-it cursor-pointer">
                <img class="off-hover unliked-116" src="/asset/img/pictogramme/LIKE - LIGHT.svg" alt="like" height="45" title="I like this">
                <img class="on-hover unlike-116" src="/asset/img/pictogramme/LIKE - DARK.svg" alt="like" height="45" title="I like this">
            </span>         
    </div>

Here is the related JS i use that does not work as expected: the src attribute change, but not classes

    $(document).ready(function () {
            $('.like-116').click(function () {
            $.post({
                url: '/en/boc/favorite/remove/1777082994'
            })
            $('.liked-116').attr({src: '/asset/img/pictogramme/LIKE - LIGHT.svg'});
            $('.liked-116').addClass('unliked-116');
            $('.liked-116').removeClass('liked-116');
            $('.like-116').addClass('unlike-116');
            $('.like-116').removeClass('like-116');
        });
        $('.unlike-116').click(function () {
            $.post({
                url: '/en/boc/favorite/add/1777082994'
            })
            $('.unliked-116').attr({src: '/asset/img/pictogramme/LIKED.svg'});
            $('.unliked-116').addClass('liked-116');
            $('.unliked-116').removeClass('unliked-116');
            $('.unlike-116').addClass('like-116');
            $('.unlike-116').removeClass('unlike-116');
        });
    });

From what i can see, this should work, not JS error are risen… Any clue?

Advertisement

Answer

Looks like this is an event delegation problem. A selector like $('.like-116') will only match elements that is currently present in DOM.

Since this is a dynamically added class and you’re executing this at $(document).ready(function () {} I don’t think these are being bound properly.

Try delegating the event handlers like:

$(document).on('click', '.like-116', function () {});

Also I don’t know if it’s intentional – you’re not waiting for the AJAX call to complete before executing further statemetns.


Try a JavaScript template literal like this everywhere:

`unliked-${training.id}`

instead of 'unliked-{{ training.id }}', unless you have some kind of magic converting this jQuery script

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement