What is the most effective way to transfer color values from one div to another?

When recreating a game similar to Mastermind, I encountered a challenge of copying color values from one div to another upon clicking a button. Despite browsing the web, I haven't found a solution for this specific situation. Below is the code I have so far:

 var colors = ["red", "blue", "yellow", "white", "black", "green", "orange", "magenta"];

 function generateSecretCode() {
   var pickedColors = [];
   while (pickedColors.length < 4) {
     var index = parseInt(Math.random() * colors.length, 0);
     var c = colors[index];
     if (pickedColors.indexOf(c) == -1) {
       pickedColors.push(c);
     }

   }
   return pickedColors;
 }

 $(function() {
   var secretCode = generateSecretCode();
   console.log(secretCode);

   var indices = [];
   $('.pickcolor').on('click', function(e) {
     var index = indices[e.target.id] ? indices[e.target.id] : 0;
     var currentColor = colors[index];
     $(e.target).css('background-color', currentColor)
       .data('data-color', currentColor);
     index = index + 1 >= colors.length ? 0 : index + 1;
     indices[e.target.id] = index;
   });

   $('#checkButton').on('click', function() {
     var selectedColors = [
       $('#choosecolor0').data('data-color'),
       $('#choosecolor1').data('data-color'),
       $('#choosecolor2').data('data-color'),
       $('#choosecolor3').data('data-color')
     ];

     if (selectedColors.indexOf(undefined) > -1) {
       alert('You haven't chosen four colors yet');
       return;
     }

   });
 });
body {
  overflow: auto;
  background-color: lightgrey;
  height: 99%;
  width: 99%;
}
/* CSS styles continue... */
 <!-- HTML content continues... -->

My goal is to copy color values from the "choosecolor" divs to the "space" divs inside the board in column order from left to right, without overlapping turns over the first column and leaving the other columns empty. I also want to ensure that there are no duplicate colors in the generated code. Additionally, I plan to implement functionality to check if the input code corresponds with the computer-generated one.

I acknowledge that verifying the input code and displaying pins corresponding to the correctness will be a separate challenge, but it's something I look forward to tackling in the future. Any tips or guidance on how to solve these issues would be highly appreciated!

Thank you in advance, Sincerely, A coding enthusiast :)

Answer №1

If you want to retrieve the color value using JavaScript, try this:

alert(myDivElement.style.backgroundColor);

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

Get the nearest H2 value in jQuery that is not a direct parent or child

In search of the h2 value closest to where the click occurred. The h2 resides within a sibling of the parent div. There are multiple div elements containing different h2 values. When a link is clicked, the nearest h2 value needs to be retrieved. <div c ...

Retrieve the content of the second <li> element using jQuery

Seeking assistance with replacing the separator symbol in a given structure. In order to proceed, I first need to identify its position. Can anyone offer guidance on how to do this? Below is the structure in question: <div> <ul> ...

Is there a way to display a different file, such as index.html, based on the screen width?

I'm facing an issue. I have completed a web page (with HTML, CSS, and JavaScript), but now I want to create a mobile version using different HTML files, another index.html file, and a separate CSS file. What changes do I need to make in the main page ...

Steps for building an API to connect to our proprietary database using the WSO2 API manager

Currently, I am looking to share my data from my personal postgresql database by creating an API. In this case, I plan on utilizing the WSO2 API manager for the process. I am uncertain if I am proceeding in the correct manner, so any advice on the differe ...

Placing a user's username within an ejs template using express and node.js

Currently, I am attempting to integrate the username into a layout using ejs templating with node and express. Below are the steps I have taken: Mongodb model: const mongoose = require('mongoose') const Schema = mongoose.Schema; var uniqueValid ...

Styling elements with CSS when the cursor hovers over them

I have a unique design challenge where I have stacked elements - an image, text, and an icon. My goal is to make only the icon animate when any of these elements are hovered over. <style> .hvr-forward { display: inline-block; vertical-align: mi ...

Modifying source dynamically in Javascript file through web.config during runtime

I have the following code snippet: <script type="text/javascript" src="path?key=1234567890"> </script> Additionally, I included the following in my web.config file: <appSettings> <add key="key" value="1234567890"/> Now, ho ...

What is the best method for incorporating new data into either the root or a component of Vue 3 when a button is pressed?

One issue I'm facing is the challenge of reactively adding data to either the Vue root or a Vue component. After mounting my Vue app instance using app.mount(), I find it difficult to dynamically add data to the application. As someone new to the fram ...

javascript accessing an external variable inside ajax function

I have implemented dajaxice to fetch a json attribute that I want to make global. However, I am facing an issue where my global variable is always showing up as "undefined": var recent_id; $(function(){ recent_id = Dajaxice.ticker.get_home_timeline(ge ...

Troubleshooting CORS Problem with AWS CloudFront Signed Cookies

I encountered an issue while implementing cloudfront signed cookies. When trying to access '' from '', the CORS policy blocked it due to absence of the 'Access-Control-Allow-Origin' header. This problem arose after rest ...

I attempted to access $.cookie but it appears to be malfunctioning

I found cookie.js on GitHub at https://github.com/carhartl/jquery-cookie and incorporated it into my code like this: $(document).ready(function(){ $("#abc").click(function() { var a = $("#text").val(); var b = $("#password").val(); alert("asdasdsd ...

Learn the process of extracting various data from a PHP source and saving it in select options through AJAX

One of the features on my website is a select option that allows users to choose a hotel name obtained from a dynamic php script. Once a hotel is selected, another select option displays room types available based on the chosen hotel. However, there seem ...

VeeValidate fails to validate input fields in a form that is constantly changing

My goal is to create dynamic forms with validations using veeValidate in Vue.js. I am attempting to achieve this by storing an array of objects within the component's data. For instance: data(){ return{ inputs: [ { id: 1, lab ...

Unexpected event triggering

I have come across a snippet of code that allows me to retrieve URL query strings var QueryURL = function () { var query_url = {}; var query = window.location.search.substring(1); var vars = query.split("&"); for (var i=0;i< ...

The margin of a single flexbox item is not aligned properly

The flexbox I have contains several items. All of them are displaying correctly except for the last one, which is expanding to the edge of the div. View the current appearance of the flexbox As shown in the image, the last element is extending to the con ...

The fading effects are not functioning as expected in the following code

Hey there, I'm not the most tech-savvy person, but I managed to come up with this code for page redirection. Unfortunately, I couldn't quite get the fade out and fade in effects to work properly when executing it. If anyone out there can help me ...

Using three.js to control the opacity and size of points

I have returned with question number two about points. My query this time revolves around changing the opacity from 0 to 1 and back within specific pixel distances from the emitter. var particleCount = 14, particles = new THREE.Geometry(), pMaterial = new ...

Assigning a class to a table row does not produce any changes

When a user clicks on a table, I am attempting to achieve two tasks using pure Javascript: Retrieve the row number (this functionality is working) Change the background color of the row Below is my current code snippet: document.querySelector('#t ...

Retrieve the URL redirected by JavaScript without altering the current page using Selenium

Is there a way to extract the URL I am supposed to be redirected to upon clicking a button on a website, without actually being redirected? The button triggers a complex Javascript function and is not a simple hyperlink. click() method doesn't meet my ...

Angular's use of ES6 generator functions allows for easier management of

Recently, I have integrated generators into my Angular project. Here is how I have implemented it so far: function loadPosts(skip) { return $rootScope.spawn(function *() { try { let promise = yield User.findAll(); $time ...