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?
addCardToInventory(playerId, gameId, cardId)will call the function directly instead of when clicked. Use anonymous function$("#" + cardId + ".card").click(function () { addCardToInventory(playerId, gameId, cardId) });functionin ananonymous function-$("#"+cardId+".card").click(function(){ addCardToInventory(playerId, gameId, cardId)});