I have a color matching game that I would like to enhance by matching background-images instead of just background-colors. However, I am facing difficulties in making this change. For instance, instead of matching the color red with the text "red," I want it to match an image representing a sports team with the name of that team.
function randomize(array) {
return array.sort(function() {
return 0.5 - Math.random();
});
};
var i = 0,
colors = randomize(["Red", "Blue", "Green", ]);
for (; i < colors.length; i++) {
$("<div>", { id: colors[i] })
.css("background-image", "url(IMAGE_URL)")
.appendTo("#colors")
.draggable({
revert: "invalid",
zIndex: 2
});
}
randomize(colors);
for (i = 0; i < colors.length; i++) {
$("<div>", { text: colors[i] })
.appendTo("#boxes");
}
$("#boxes > div").droppable({
accept: function(draggable) {
return $(this).text() === draggable.attr("id");
},
drop: function(event, ui) {
var imageUrl = ui.draggable.css("background-image");
$(this).css("background-image", imageUrl).addClass("filled");
ui.draggable.hide("puff");
if ($(".filled").length === colors.length) {
alert("Good Job!");
setTimeout(function() {
window.location = window.location;
}, 3000);
}
}
});
#colors {
position: absolute;
margin-left: 400px;
}
.ui-draggable {
width: 100px;
height: 100px;
margin: 20px;
cursor: pointer;
border: 1px solid black;
box-sizing: border-box;
}
#boxes {
position: absolute;
left: 200px;
}
#boxes > div {
border: 1px solid black;
height: 100px;
width: 100px;
margin: 20px;
text-align: center;
padding-top: 40px;
box-sizing: border-box;
line-height: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<h2>Color Match Game</h2>
<div id="colors"></div>
<div id="boxes"></div>