Problem Description (See Fiddle):
When clicking on the red boxes, they transform into kittens and display an alert with the current value of i
. Clicking on a large fading kitten will reset everything.
I am puzzled as to why alert(i)
is triggering multiple times, increasing exponentially with each pass after the first click. I am also unsure of how to prevent this behavior. Initially, I thought it was due to creating new DOM elements, but since I'm only changing the img
source, I am not certain.
If you find any issues or inefficiencies in my code, please do point them out to me. I welcome suggestions on more elegant solutions.
Code:
cats = [
"http://placekitten.com/g/121/121",
"http://placekitten.com/g/122/122",
"http://placekitten.com/g/123/123",
"http://placekitten.com/g/124/124",
"http://placekitten.com/g/125/125",
"http://placekitten.com/g/126/126",
"http://placekitten.com/g/127/127",
"http://placekitten.com/g/128/128",
"http://placekitten.com/g/129/129",
"http://placekitten.com/g/130/130"
];
count = 0;
function getRandomCats() {
var kitties = [];
for(i = 0; i < 3; i++) {
rand = Math.floor(Math.random() * (9 - 0 + 1)) + 0;
kitties[i] = cats[rand];
}
meow(kitties);
}
function meow(kitties) {
$('.cats').each(function(i) {
$(this).mousedown(function() {
alert(i); //debug
$('div.front img', this).attr('src', kitties[i]);
$(this).css({
'transform': 'rotateY(180deg)',
'-webkit-transform': 'rotateY(180deg)',
'transition': 'transform 500ms ease-in-out',
'-webkit-transition': '-webkit-transform 500ms ease-in-out'
});
this.flipped = 1, this.locked;
if (this.flipped && !this.locked) {
this.locked = 1;
count++;
if (count > 2) {
$('#newCat').fadeIn();
}
}
})
});
}
var clicked = 0;
$('#newCat').mousedown(function() {
if (clicked == 0) {
clicked = 1;
$(this).stop(true).fadeOut();
$('.cats').fadeOut(1000, function() {
this.flipped = 0, this.locked = 0, count = 0;
$(this).hide().css({
'transform': 'rotateY(0deg)',
'-webkit-transform': 'rotateY(0deg)'
});
getRandomCats();
$(this).fadeIn();
});
}
setTimeout(function(){clicked = 0;}, 1000);
});
getRandomCats();