siannone
siannone

Reputation: 6763

jQuery hasClass() function not working after element is updated

I have created a button that allows the users of my platform to upvote a post or remove the previously cast vote it if the button is pressed again.

The problem is that when the user clicks the button the second time, after the post has been voted nothing happens.

This is the code that manages the button's behavior:

if($(".timeline-action-plus").hasClass("btn-success")) {
    $(".timeline-action-plus").click(function(){
        rating.removeVote($(this).data("entry-id"), $(this).data("token"));
    });
} else {
    $(".timeline-action-plus").click(function(){
        rating.votePlus($(this).data("entry-id"), $(this).data("token"));
    });
}

The removeVote and votePlus functions also take care of modifying the button's aspect:

function votePlus(id, token) {

    $.post(
        "http://localhost/user/vote",
        {
            rating  : '1',
            entryID : id,
            _token  : token
        },
        function(result) {
            if(result === "OK"){
                $(".timeline-action-plus[data-entry-id=" + id + "]").removeClass("btn-default");
                $(".timeline-action-plus[data-entry-id=" + id + "]").addClass("btn-success");
            }
        }
    );
}

function removeVote(id, token) {
    $.post(
        "http://localhost/user/removeVote",
        {
            entryID : id,
            _token  : token
        },
        function(result) {
            if(result === "OK") {
                $(".timeline-action-plus[data-entry-id=" + id + "]").removeClass("btn-success");
                $(".timeline-action-plus[data-entry-id=" + id + "]").addClass("btn-default");
            }
        }
    )
}

Basically the $(".timeline-action-plus").hasClass("btn-success") seems to work only before that the button classes are updated by the removeVote and votePlus functions.

Edit:

This is the button:

<button class="btn btn-xs @if(Rating::userHasVoted(Auth::user()->username, $article->id)) btn-success @else btn-default @endif timeline-action timeline-action-plus" data-entry-id="{{$ID}}" data-toggle="tooltip" data-token="{{csrf_token()}}" id="vote{{$ID}}" Title="+1">
    <span class="glyphicon glyphicon-thumbs-up"></span>
    <span id="voteNumber{{$ID}}"></span>
</button>

Upvotes: 3

Views: 1029

Answers (1)

James Donnelly
James Donnelly

Reputation: 128791

You need to move the hasClass check inside your click function:

$(".timeline-action-plus").click(function(){
    if ($(this).hasClass("btn-success")) {
        rating.removeVote($(this).data("entry-id"), $(this).data("token"));
    else
        rating.votePlus($(this).data("entry-id"), $(this).data("token"));
});

This will now perform the check every time the element is clicked.

Upvotes: 7

Related Questions