Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My jQuery only works after page refresh

My website has a list of games. One feature is being able to "watch" games. It's working well, but I can't reverse an action (watch/unwatch) unless I refresh the page.

Here's my jQuery:

$('.watch').click(function(e) {

    e.preventDefault();

    var game_id = $(this).data('game_id');
    $('#game-' + game_id + ' .watch').addClass('unwatch').removeClass('watch');

});

$('.unwatch').click(function(e) {

    e.preventDefault();

    var game_id = $(this).data('game_id');
    $('#game-' + game_id + ' .unwatch').addClass('watch').removeClass('unwatch');

});

Any ideas? Perhaps I can improve my code as well? Still learning jQuery/Javascript.

Thanks!

like image 867
Scully Avatar asked Jan 02 '26 00:01

Scully


1 Answers

When you write the line $('.watch').click(callback); you attach callback to all element having .watch class at the moment of that line execution. When you change later the class of an element from .watch to .unwatch, it is not attached to callback you setted for .unwatch elements before.

You need to have a class .game for all you games and then :

$('.game').click(function(e) {

    e.preventDefault();

    var game_id = $(this).data('game_id');

    if($('#game-' + game_id).hasClass('unwatch')) {
        $('#game-' + game_id).addClass('watch').removeClass('unwatch');
    } else if ($('#game-' + game_id).hasClass('watch')) {
        $('#game-' + game_id).addClass('unwatch').removeClass('watch');
    }
});
like image 100
jillro Avatar answered Jan 03 '26 14:01

jillro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!