Utilizing a CSS/HTML div grid to mirror a 2D array in JavaScript

Currently, I am working on a personal project that involves creating a grid of divs in HTML corresponding to a 2D array in JavaScript. However, I am uncertain about the most effective way to accomplish this task.

Specifically, what I aim to achieve is that when a div in the grid is clicked, it should change color and modify a number in the array from 0 to 1 (or vice versa). Although there are other numbers involved, this is the basic functionality.

I believe using an onClick listener to change the class of the div would be the optimal approach to handle the color change, but how can I establish a connection between the array and the grid?

Thank you in advance for any assistance you can provide.

Answer №1

To interact with elements in the DOM and an array, you can use indexing.

var colorsArray =[
  {color:'blue', num:0},
  {color:'green',  num:0}
];

$(function(){
  var $boxes =  $('.box-class').click(function(){
     var boxIndex = $boxes.index(this);
     $(this).css('backgroundColor', colorsArray[boxIndex].color);
     colorsArray[boxIndex].num ++;
     console.log(colorsArray);
  });
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box-class">Click me - item #1</div>
<div class="box-class">Click me - item #2</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

Flexible array for varying results

I'm attempting to display a random selection from two arrays by alternating between them, with no concern for storage capacity. Unfortunately, my code is not functioning correctly and I am unsure why. var male = ["have a shot", "item 2", "item 3"]; ...

issue with accessing instant state modification via useEffect

I am currently learning about React Hooks While I try to render a list from an array and remove the first element on click, the state gets updated in the handleclick function but it doesn't render correctly export default function App() { const [na ...

The Angular Material Datepicker lacks any selected date

I am currently in the process of developing a web application using Angular and incorporating Angular Material for certain UI components. I have encountered an issue that I am unable to resolve. When attempting to use the datepicker as outlined on https:// ...

Take away the follow option on the embedded tweet

I need to customize the appearance of embedded tweets on a website by removing the follow button as well as the reply, favorite, and retweet buttons in the footer. Here is a simple HTML example: <blockquote class="twitter-tweet"> <a href="htt ...

Replacing text within nested elements

I am facing an issue with replacing certain elements on my webpage. The element in question looks like this: <div id="product-123"> <h3>${Title}</h3> <div> ${Description} </div> <div> ${P ...

Iterating through a JSON object to verify the presence of a specific value

I have a JSON Object and I am looking for a way in Angular 6 to search for the value "Tennis" in the key "name". Can you provide guidance on how to achieve this? { "id":2, "name":"Sports", "url":"/sports" "children":[ { "id":1, ...

The Challenge of a Chess Board that Adjusts to Different

Looking at the demonstration below, it's clear that the chessboard adjusts properly to a width of no more than 512px while adapting to different devices. The pieces also resize accordingly with the board. However, I'm encountering an issue when a ...

The spacing within the table's <tr> elements does not get altered

I am struggling to add a small space in the table <tr> but my attempts have not been successful. How can I resolve this issue? Please refer to the image below for clarification: https://i.sstatic.net/HXdhq.png .panel-booking .panel-body { pad ...

Ways to include extra information in a request when uploading images using Django's CKEditor?

On my website, I am utilizing django-ckeditor to allow users to input rich text content. Each webpage on the site represents a unique document identified by an id. For instance, two different documents will have separate webpages with URLs like - exampl ...

IE Troubles: Timer Function Fails in Asp.Net MVC

I implemented the following code snippet: @Using Ajax.BeginForm("Index", New AjaxOptions() With { _ .UpdateTargetId = "AnswerSN", .HttpMethod = ...

Tips on utilizing innerHTML or innerText to add content to the Evernote editor, a rich text editor

A method authored by Jayant was employed in this particular post how-to-insert-text-into-the-textarea-at-the-current-cursor-position to perform an insertion into the Evernote editor. The Evernote editor being a rich text editor, altering from el.value to ...

Manipulate the DOM to remove a checkbox using JavaScript

I'm brand new to exploring the world of Javascript and could use some guidance with this task. I have a collection of checkboxes that I'd like to manipulate so that when one is checked, it disappears from the list automatically. I've come ac ...

Is there a way to automatically hide divs with the style "visibility:hidden" if they are not visible within the viewport?

Currently, I am working on developing a mobile web app. Unfortunately, Safari in iOS 5.1 or earlier has limited memory capabilities. In order to reduce memory usage while using css3 transitions, I have discovered that utilizing the css styles "display:none ...

How to retrieve the selected value from multiple JQuery UI Autocomplete boxes?

I have implemented three jQuery UI 'Autocomplete' input fields on a single page: <select id="combobox1"><?php putSome1ValuesHere(); ?></select> <select id="combobox2"><?php putSome2ValuesHere(); ?></select> &l ...

Display a page with sections that have opacity applied, identified by the hashtag #section, and utilize JavaScript to automatically scroll to the top of

Check out my app at . I'm working on overriding the scroll bar behavior in CSS to keep the entire app visible, including the logo, header, and controls, as users navigate through different sections. However, I seem to be having trouble with the CSS as ...

Unfortunate escapement of characters discovered in variable that returns JSON image source

I am currently utilizing Google Tag Manager to incorporate the 'article' JSON markup and retrieve different variables for modifying specific sections on particular pages. Among the elements I am attempting to obtain is the image source. At prese ...

Creating a webpage with HTML through C++

I've been experimenting with posting an HTML page using C++. I created a class that utilizes sockets to implement TCP socketing. After checking, it seems like the issue lies in what I am sending: string s = "<!DOCTYPE html><html><head& ...

What is the process for setting environment variables in a Svelte project?

I'm brand new to working with Svelte and I want to incorporate environment variables like base_url into different components. I've read that I can set up a store to hold these values, for example: const DataStore = writable([ { base_url: & ...

Error: The function you are trying to reference is undefined

I am facing an issue where I am receiving a "ReferenceError: doNotification is not defined" message when attempting to display a pop-up notification upon successful promise. Oddly enough, triggering doNotification on button click within my HTML works wit ...

X-editable does not verify if the checklist values are checked

Hello everyone, currently I am working on a Laravel project where I have implemented the X-editable library for inline editing functionalities. I am facing an issue with updating a many-to-many relationship table (pivot table) and I am trying to use the X- ...