Reputation: 1079
$('#stuff_btn').on('click', function(event){
event.preventDefault();
$(this).remove();
$('#stuff').prepend('<div id="current_lvl">Level: 1</div>');
var words = ["arvuti","pudel","ekraan"];
var random = Math.floor(Math.random() * words.length);
var word = words[random];
var chars = word.split('');
chars = _.shuffle(chars);
for(var i in chars)
{
$('#word_place_grid ul').append('<li id="letter' + i + '">' + chars[i] + '</li>');
$('#letter'+i).bind('click',function(){
$(this).animate({
opacity: 0.30,
top: -55,
},750,function(){ //Animation complete
$('#game_window_grid ul').append('<li>' + chars[i] + '</li>');
$(this).remove();
});
});
}
})
HTML:
<div class="word_grid" id="game_window_grid">
<ul>
</ul>
</div>
<div class="word_grid" id="word_place_grid">
<ul>
</ul>
</div>
So I am trying to take a word randomly from the list. Shuffle the letters. Put each letter to a separate li in the dic #word_place_grid. Then I wan to add the click handler to each div that would animate that li and in the end of the animation I would like to add the value of the animated li to a new li element that I append to the div #game_window_grid. The problem is that with the jQuery code I have right now, it will add the last random character from the list: chars to all of the li elements that I add to the div #game_window_grid. No matter which way I try to rewrite the code, I still cant get the right value for li.
Any idea what I should change or what should I do to get the correct value for the div #game_window_grid li ?
Thanks in advance
Upvotes: 0
Views: 115
Reputation: 960
Pull this out...
$('#letter'+i).bind('click',function(){
$(this).animate({
opacity: 0.30,
top: -55,
},750,function(){ //Animation complete
$('#game_window_grid ul').append('<li>' + chars[i] + '</li>');
$(this).remove();
});
});
Put this somewhere else...
$('#word_place_grid').on('click', '[id^=letter]', function(){
var character = $(this).text();
$(this).animate({
opacity: 0.30,
top: -55,
},750,function(){ //Animation complete
$('#game_window_grid ul').append('<li>' + character + '</li>');
$(this).remove();
});
});
Edit: Alternatively you can get rid of the for...in loop and replace with $.each()
as your iterator
$.each(chars, function(i, character) {
$('#word_place_grid ul').append('<li id="letter' + i + '">' + character + '</li>');
$('#letter'+i).on('click',function(){
$(this).animate({
opacity: 0.30,
top: -55,
},750,function(){ //Animation complete
$('#game_window_grid ul').append('<li>' + character + '</li>');
$(this).remove();
});
});
});
P.S. .bind()
is not as widely used as of jQuery 1.7 .on()
contains the same functionality with the added benefit of delegated events that can occur after the page is loaded (this is how my original answer works to find the dynamically added elements [id^=letter]
Upvotes: 1