Reputation: 976
I am working on a memory matching game. I have some code that checks if two images that the user clicked on have the same source and removes the images if they do have the same source.
(function compareClicked() {
var lastclicked = "";
$("img").click(function() {
var path = $(this).attr("src");
if( lastclicked == path) {
$('img').hide(1000, function () {
$(this).remove();
});
}
else {
if( lastclicked != "") alert("Not a match");
}
lastclicked = path;
});
})();
However, as you can see, when they have the same source, it removes all of the images on the page - even if the user did not click any them. How can I change it so it only removes the two images that the user clicked on?
Upvotes: 2
Views: 113
Reputation: 4293
How about something like
var lastEl = null;
$(document).ready(function(){
$('img').each(function(index){
$(this).attr('id','img-' + index);
});
$('img').click(function(){
if( lastEl ) {
if( ($(this).attr('src') == lastEl.attr('src')) && ($(this).attr('id') != lastEl.attr('id')) ) {
$(this).remove();
lastEl.remove();
}
lastEl = null;
} else {
lastEl = $(this);
}
});
});
Haven't tested that, but it's got to be pretty close
EDIT: Updated code in line with conversation below. JS fiddle here http://jsfiddle.net/joevallender/pc3Qa/3/
EDIT again: JS fiddle link should be correct now
Upvotes: 2
Reputation: 87073
var lastclicked = "";
$("img").click(function() {
var path = $(this).attr("src"); // or this.src
if (lastclicked == path) {
$(this).hide(1000, function() {
// remove image with same src as lastClicked
$('img[src="' + lastclicked + '"]').remove();
});
} else {
if (lastclicked != "") alert("Not a match");
}
lastclicked = path;
});
Upvotes: 6
Reputation: 10294
If you got multiple time (more than twice) the same Src, I really suggest that you tag
your clicked images to know which one should be hidden.
As mentionned you could use attr
or special class
for this purpose.
Upvotes: 2