Transform this color matching game into an image matching game using JavaScript and jQuery

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>

Answer №1

Below is a fully functional example:

I have modified the colors array to now consist of objects, each containing a key and URL. The code has been adjusted accordingly to use these properties instead of plain values.

function randomize(array) {
  return array.sort(function() {
    return 0.5 - Math.random();
  });
};
var i = 0,
  colors = randomize([{
    url: 'http://rs556.pbsrc.com/albums/ss3/t_wangrung/Fruit/09.jpg~c200',
    key: 'green'
  }, {
    url: 'https://static1.squarespace.com/static/58f993b51e5b6cd8b70dba67/t/59161cb886e6c0d270d975da/1494621371074/',
    key: 'blue'
  }, {
    url: 'http://www.dhresource.com/200x200s/f2-albu-g5-M01-0E-49-rBVaI1kw5WmAdqUmAAIKTn2gGls240.jpg/10pcs-bag-hot-sale-dark-red-cherry-seeds.jpg',
    key: 'red'
  }]);
for (; i < colors.length; i++) {
  $("<div>", {
      id: colors[i].key
    })
    .css("background-image", "url(" + colors[i].url + ")")
    .appendTo("#colors")
    .draggable({
      revert: "invalid",
      zIndex: 2
    });
}
randomize(colors);
for (i = 0; i < colors.length; i++) {
  $("<div>", {
      text: colors[i].key
    })
    .appendTo("#boxes");
}
$("#boxes > div").droppable({
  accept: function(draggable) {
    return $(this).text() == draggable.attr("id");
  },
  drop: function(event, ui) {
    var color = ui.draggable.css("background-image");
    $(this).css("background-image", color).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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize checkboxes to sort through MySQLi data

Currently, I have a page that is populated with various types of posts such as news and blog entries. My goal is to implement checkboxes so that users can select which type of post they want to view. For example, I would like the option to check 'new ...

Steps to reveal a child element when the parent is set to overflow:hidden

There seems to be an issue with a child element having overflow:visible; while the parent element has overflow:hidden;. The height of the child element exceeds that of the parent element. Why is the child element hidden even when its overflow property is ...

Differences in background-size among various browsers

Having some trouble with scaling backgrounds on different browsers. Initially designed website on Google Chrome, but background doesn't scale properly when viewed on iPhone or older versions of IE. Started with: background-size: 100% 150%; Then c ...

Encountered issues loading JavaScript and received a pyppeteer error while trying to access a website through requests

I am facing a challenge when trying to scrape a webpage post login using BeautifulSoup and requests. Initially, I encountered a roadblock where the page requested JavaScript to be enabled to continue using the application. To work around this issue, I de ...

Unable to access current props within useEffect block

When I use useEffect with the parameter props.quizStep, my function fn (which is a keydown event listener) is unable to access the current value of props.quizStep. I'm puzzled as to why it's not working properly. Can you help me understand? Bel ...

No location matched any routes

I'm currently working on a notes application, and I've encountered an error when trying to edit the notes. The error message says "No routes matched location id ...". Any idea what could be causing this issue? The approach I'm taking is to ...

Pass data between JavaScript and PHP using the Phaser framework

I am trying to pass a JavaScript variable to PHP and then store it in a database. Despite searching for solutions on Google, I have not been successful. Most suggestions involve using AJAX, but the code doesn't seem to work when I try it. I attempted ...

invoking a function through prototype

<script> var Nancy = function(){ this.name = 'nancy' } Nancy.prototype.getNancy = function(){ alert(this.name); } Nancy.prototype.getNancy(); function Bob(){ ...

Populate Dynamically Generated Tabs with Data using jQuery AJAX and PHP

My current scenario is: A PHP script is fetching data from a database, which is then displayed in the first tab. This tab remains fixed and cannot be closed. The code for this is working fine as it is. try { print ' <div class="clientTabs"&g ...

CSS only accordion divs that are all opened by default with no need for jquery

My current setup involves: jsfiddle.net/wromLbq5 I would like to enable the functionality of having multiple accordion sections open simultaneously upon page load. This means that when one section is opened, the others should not close. Is there a way to ...

The PHP-based registration process is malfunctioning

Trying to simply register, but I'm encountering an issue where the file is named Login.html/.php instead of just Login.html. Below is my HTML form in Login.html: <!DOCTYPE html> <html> <head> <title>Register/ Login</title&g ...

Changing Settings on the Fly with JQuery

I am facing an issue with a table that has values generated dynamically using PHP, such as id and name attributes (e.g. id="question_". My challenge is how to set an element attribute considering this dynamic nature. For instance, I need to update the tex ...

When implementing the Slick Carousel with autoplay within an Isotope grid, the height of the image slides may occasionally reduce to 1 pixel when applying filters

I've been struggling with this issue for more than a day now, and despite searching through similar posts and trying their solutions, I still haven't been able to resolve it. Here's an example of the problem: https://jsfiddle.net/Aorus/1c4x ...

EJS.JS Error: Unable to find the title

I'm facing an issue with a script in express. I have a function that renders a view upon the success of another function. This project involves angular, node, express, and ejs as the view engine. However, when I try to render the view, I encounter an ...

How can you create a scenario in Angular Material where items in a toolbar transition to the second line exclusively on mobile screens?

Visit the Angular Material website to see how the toolbar appears on a desktop: https://material.angular.io/ On mobile devices, the menu items Components, CDK, and Guides are displayed on the second line, while github, theme icon, and version number dropd ...

The ever-changing world of list items with dynamic editions

One of my tasks involves displaying a list of elements through the ng-repeat directive. Each element is contained within its own div block. My goal now is to enable editing for each block, so that when users click on an edit button, the content of the div ...

What could possibly be causing the "Unexpected token (" error to appear in this code?

Sorry if this appears as a typo that I am struggling to identify. My browser (Chrome) is highlighting the following line <a class="carousel-link" onclick="function(){jQuery('#coffee-modal').modal('show');}">Book a coffee</a> ...

What is the best way to retrieve the second element based on its position using a class name in Jquery?

DisablePaginationButton("first"); The statement above successfully disables the first element that is fetched. DisablePaginationButton("second"); ===> not functioning function DisablePaginationButton(position) { $(".pagination a:" + position).ad ...

When running the "react-scripts build" command and then serving it, the HTML files are being served instead

After successfully generating the build folder using react-scripts and running npm run build, I attempted to serve it locally with the npm package called serve by running serve -s build. The serve command started running on port 5000 without any issues. ...

flexbox wrapping text styling

Can text be wrapped in flex within a fixed width container? For example: img username added you as a friend Instead of: user added img name you as a friend I am able to achieve this if the image and 'a' were separat ...