wUmpage
wUmpage

Reputation: 165

AJAX jQuery .click Element running function on load instead of click

Maybe i'm just a jQuery noob, but I don't understand why when I set an elements .click event it runs when the element loads.

Code:

//Deal Cards button
$(".draw-cards").click(function(){
    var playerId = 1;
    var gameId = 20;
    $.ajax({
        type: 'GET',
        url: './system/actions/draw.php',
        data: "playerId=" + playerId,
        success: function(data) {
            //Post to Player Card container
            $('#player-cards').html(data);
            //Resize Fonts
            fontSize();
            //For each loaded check if usable
            $( ".card" ).each(function() {
                var cardId = $(this).attr('id');
                comparePlayerCard(cardId, function(data) {
                    console.log(data);
                    if (data == 1){
                        $("#"+cardId+".card").css('box-shadow', '0px 0px 12px 6px #00ff40');
                        $("#"+cardId+".card").click(addCardToInventory(playerId, gameId, cardId)); // <---- PROBLEM CODE
                    }
                });
            });
        }
    });
});

The function inside

$("#"+cardId+".card").click(addCardToInventory(playerId, gameId, cardId));

Is being run when the element loads through the AJAX, then it doesn't work when I click the element. Not sure why.

Any suggestions?

Upvotes: 0

Views: 299

Answers (1)

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34244

You shouldn't pass function call this way.

It should be an anonymous function:

$("#"+cardId+".card").click(function() {
    functionaddCardToInventory(playerId, gameId, cardId);
});

It is usually the most suitable approach, but it is a bad practice to use anonymous functions within a loop.

Or it can be a function without arguments:

$("#" + cardId + ".card").click(functionaddCardToInventory);

In this case, you can describe your values as a global values or within data attributes:

HTML:

<div id="cardId" class="card" data-game-id="7" data-card-id="11"></div>

JS:

var playedId = 14;    

function functionaddCardToInventory()
{
    var cardId = $(this).data("card-id");
    var gameId = $(this).data("game-id");
    // and playerId is global
}

// Function without arguments can be passed this way
$("#" + cardId + ".card").click(functionaddCardToInventory);

Upvotes: 3

Related Questions