Reputation: 157
I have written the following code: http://jsfiddle.net/2YL8Q/5/
var $button = $("button");
var $buttonClicked;
var $instructionText = $("#instructionText");
var $item = $("li");
var $firstItemPicked;
var $secondItemPicked;
var $firstItemIndex;
var $secondItemIndex;
var $clonedItem;
$button.on("click", function () {
$buttonClicked = 1;
$instructionText.html("Instructions: Pick an item");
});
$item.on("click", function () {
if ($buttonClicked === 1) {
$firstItemPicked = $(this);
$firstItemPicked.addClass("selected");
$firstItemIndex = $item.index($(this));
$instructionText.html("Instructions: " + $firstItemPicked.text() + " has been picked, now pick another to swap places with");
$buttonClicked = 0;
alert($firstItemIndex);
} else if ($buttonClicked === 0) {
$clonedItem = $(this).clone();
$secondItemPicked = this;
$($secondItemPicked).after($($clonedItem));
$($firstItemPicked).after($($secondItemPicked));
$($clonedItem).after($($firstItemPicked));
$($firstItemPicked).removeClass();
$($clonedItem).remove();
$buttonClicked = 2;
$secondItemIndex = $item.index($firstItemPicked);
alert($secondItemIndex);
if (($firstItemIndex + 1) <= 4 && ($secondItemIndex + 1) <= 4) {
$instructionText.html("First picked item came from list #1 and ended up in list #1");
}
if (($firstItemIndex + 1) > 4 && ($secondItemIndex + 1) <= 4) {
$instructionText.html("First picked item came from list #2 and ended up in list #1");
}
if (($firstItemIndex + 1) <= 4 && ($secondItemIndex + 1) > 4) {
$instructionText.html("First picked item came from list #1 and ended up in list #2");
}
if (($firstItemIndex + 1) > 4 && ($secondItemIndex + 1) > 4) {
$instructionText.html("First picked item came from list #2 and ended up in list #1");
}
}
});
The only thing missing is to output where from the first picked item came from and where it ended up. It doesn't seem to work when I'm picking the first item from list #1 and swapping with an item from list #2. Though it works when I'm swapping first from #2 to #1.
Any help on what I'm doing wrong here?
Upvotes: 0
Views: 65
Reputation: 33870
Because when getting your second index, you are getting the index of the first selected element again.
change your line to
$secondItemIndex = $item.index($secondItemPicked);
And it work : http://jsfiddle.net/2YL8Q/9/
Upvotes: 1