teknek teknek - 1 month ago 11
jQuery Question

Trying to use appendTo() to push dives to one part of a page, after a first appendTo() is done.

I am trying to create a game where the user has 4 pictures to choose from, once a character is selected the other 3 images are pushed to a new section where the user then selects a character to fight. What should happen next is that once that character is selected from the enemy select area it would then be pushed to a new area where it would fight the original character that is selected.

Currently I can get the character select and the staging area for the enemy to fight to work. It seems however once an enemy is selected it just breaks the whole thing and pushes all the characters to the enemy staging area, I am having trouble figuring out how to make it work so once an enemy is in the staging area that it would then be able to be selected and then pushed to the fighting area. Thanks for the help, heres what I have so far:

$(document).ready(function(){

var char ="";
isChosen = false;
ifattacker = false;


$(".defender").click(function(){ //trying to figure out how to select a character

if (isChosen) return;

($(".frodo").on("click",function(){
$(".gandalf").appendTo(".enemy-select1");
$(".balrog").appendTo(".enemy-select2").addClass("attacker");
$(".sauron").appendTo(".enemy-select3").addClass("attacker");
}));

($(".gandalf").on("click",function(){
$(".frodo").appendTo(".enemy-select1");
$(".balrog").appendTo(".enemy-select2");
$(".sauron").appendTo(".enemy-select3");
}));

($(".balrog").on("click",function(){
$(".frodo").appendTo(".enemy-select1");
$(".gandalf").appendTo(".enemy-select2");
$(".sauron").appendTo(".enemy-select3");
}));

($(".sauron").on("click",function(){
$(".frodo").appendTo(".enemy-select1");
$(".gandalf").appendTo(".enemy-select2");
$(".balrog").appendTo(".enemy-select3");
}));

}); // end characters click

$("attacker").click(function(){

isChosen = true;

($(".gandalf").on("click",function(){
$(".gandalf").appendTo(".attack")
}));

});


}); // end document ready

Answer

I'm noticing two issues, one of which I believe is the issue, the other a simple syntax error.

1. You are binding a click event to Gandalf when .defender is clicked. When .attacker is clicked, you're binding another event to Gandalf. This does not replace the original event, it adds to it, and so clicking Gandalf will re-fire the initial event. What you may wish to do is:

$(".attacker").click(function(){

    isChosen = true;
    //Unbind the previous click event using .off() before binding new event
    $(".gandalf").off().on("click",function(){
        $(".gandalf").appendTo(".attack")
    });

});

2. In the above snippet, I added a . to your attacker selector, because I assume you wanted to bind that to the click of the attacker class. Should be $(".attacker").