0

I have 2 functions in my javascript file for liking and unliking a post:

$('.post-like-link').click(function() {
    const element = $(this);
    $.getJSON(
        Routing.generate('likes_like', {'id': $(this).attr("data-post-id")}),
        function (data) {
            element.removeClass(['btn-white', 'post-like-link']);
            element.addClass(['btn-outline-primary', 'post-unlike-link']);
            element.children().first().next().text(data['count']);
        }
    );
});

$('.post-unlike-link').click(function() {
    const element = $(this);
    $.getJSON(
        Routing.generate('likes_unlike', {'id': $(this).attr("data-post-id")}),
        function (data) {
            element.removeClass(['btn-outline-primary', 'post-unlike-link']);
            element.addClass(['btn-white', 'post-like-link']);
            element.children().first().next().text(data['count']);
        }
    );
});

And a button in my HTML

<a href="#!" data-post-id="{{ post.id }}" class="btn btn-sm btn-{% if isLiked %}outline-primary post-unlike-link{% else %}white post-like-link{% endif %}">
                        <span class="fe fe-thumbs-up mr-2"></span>
                        <span id="post-like-count">{{ post.getLikedBy.count }}</span>
                    </a>

When I click the like button in my HTML the corresponding function (like) is called. However if I click it again it should call the other function (unlike) as the class gets updated, but it doesn't it, calls the same function (like) again. Can anyone advise why this is happening please?

Shaun
  • 173
  • 2
  • 12
  • 1
    `$('.post-unlike-link').click(` and like calls only apply to elements at the time of calling not future elements. You need to use a delegated event – Patrick Evans Jul 11 '20 at 23:41
  • [Understanding Event Delegation](https://learn.jquery.com/events/event-delegation/) – charlietfl Jul 12 '20 at 00:15

0 Answers0