modify the color of a box within a grid upon clicking it

I am curious if it is possible to change the color of a box when it is clicked.

I am working on coding a "calculator layout" and would like to start with this part

1 2 3
4 5 6
7 8 9
  0

This is what I have been working on and struggling with.

$(document).ready(function() {
  $("#k1").click(function() {
    $("#k1").backgroundcolor = 'red';
  });
});
.grid-container {
  display: grid;
  grid-template-columns: auto auto auto;
  gap: 10px;
  background-color: #c5c5c5;
  padding: 10px;
}

.grid-container>div {
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid black;
  text-align: center;
  font-size: 30px;
}

.it0 {
  grid-column-start: 2;
  grid-column-end: 3;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="grid-container">
  <div id="k1" class="it1">1</div>
  <div id="k2" class="it2">2</div>
  <div id="k3" class="it3">3</div>
  <div id="k0" class="it0">0</div>
</div>

Answer №1

Your coding skills are definitely improving! However, there are some minor adjustments required in your JavaScript code. Here is the revised version of your code that will modify the color of a box upon clicking:

$(document).ready(function() {
  $("#k1").click(function(){
    $(this).css('background-color', 'red'); // Update the background color of the clicked element
  });
});

In the given snippet, $(this) specifically targets the clicked element, and .css('background-color', 'red') is utilized to change its background color to red after being clicked.

You can follow a similar methodology for other boxes too. For instance, if you wish to alter the color of the box with id k2 to blue upon clicking, implement the following lines of code:

$("#k2").click(function(){
  $(this).css('background-color', 'blue');
});

This same technique can be replicated for the remaining boxes to adjust their background colors upon clicking as necessary.

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

Creating an HTML table syntax from a PHP 2-dimensional array

I am looking for a way to extract data from a bi-dimensional array and display it in an HTML table format. Here is an example of the array: $grid = array( array(0,0,0,0),array(0,0,0,0),array(0,0,0,0),array(0,0,0,0),array(0,0,0,0)); $grid[0][0]=4;$grid[0][ ...

Incorrect formatting of HTML emails in Outlook

I crafted an html e-mail using the code below: <!DOCTYPE html> <html style="margin:0px;padding:0px;"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"> </head> <body style="mar ...

Steps for adding JSON array information to the tbody of an HTML table

I am a beginner in the world of jQuery and JSON, seeking guidance on parsing a JSON file in order to populate an HTML table's tbody section: {"response":[["name0","id0","amt0"],["name1","id1","amt1"]]} I am struggling to figure out how to access thi ...

Ensuring Radiobuttons are Selected on a Page After Clicking the Submit Button

Seeking assistance with this issue: I am working on a page that includes radio buttons: <label>Delivery type:</label> <input type="radio" name="delivery" value="7" class="delivery-item" id="del-type-7" onclick=""><label class="label" ...

Guide to showcasing an image on an HTML page using HTTP header

I have an HTML page with a basic layout that includes a single button. When this button is clicked, it needs to trigger an HTTP request to a specific URL while including an Accept header for GET requests. The response from the HTTP URL will vary depending ...

What is the best way to replicate a synchronous ajax call? (mimicking synchronous behavior with asynchronous methods)

Given that a "native" synchronous ajax call can block the user interface of the browser, it may not be suitable for many real-world scenarios (including mine). I am curious to know if there is a way to mimic a synchronous (blocking) ajax call using an asy ...

Translate a jQuery ajax request utilizing jQuery().serialize into plain JavaScript

Currently, I've been in the process of converting a jQuery script into vanilla JavaScript to completely eliminate the need for jQuery. The main functionality of the code includes: Upon clicking a button on the front end, an ajax request is sent, upda ...

Transferring information through AJAX and fetching through PHP

Below is my current AJAX code setup: optionScope.data().stage = 'b'; $.ajax({ url: "functions/contact.php", type: "post", data: {'stage': optionScope.data().stage}, success: function(data, status) { ...

What methods are available for parsing JSON data into an array using JavaScript?

I possess an item. [Object { id=8, question="وصلت المنافذ الجمركية في...طنة حتّى عام 1970م إلى ", choice1="20 منفذًا", more...}, Object { id=22, question="تأسست مطبعة مزون التي تع... الأ ...

Tomcat encounters difficulty accessing the JavaScript directory

Seeking assistance with my first question regarding Angular tutorials. When I deploy to test the script, I encounter an HTTP 404 error. I have tried various solutions suggested for similar issues without success. It appears to be a path problem as the ang ...

Preserve jQuery-enhanced webpage changes permanently

I am looking to permanently save modifications made on an HTML page using JQuery. I have come across suggestions about achieving this by sending an Ajax call and storing the data in a database table. However, I am unsure about what exactly needs to be save ...

Get rid of the spaces in web scraping <tr> tags using Node.js

I've encountered a problem that goes beyond my current knowledge. I'm attempting to web-scrape a specific webpage, targeting the <tr> element in nodejs. Although I can successfully retrieve the content, it seems that the format is not as cl ...

Error encountered: 'applePaySession.completeMerchantValidation' is not a valid object reference when attempting to process a successful apple pay payment

So, I'm having an issue with the user's payment going through but encountering undefined value when checking compatibility. I've been trying to debug this problem in my code snippet below: setCanDisplayApplePay() { var client = n ...

The problem with Ajax POST is occurring in Firefox and Chrome, but not in IE8

I am encountering an issue with the code snippet provided below. Upon executing it in Internet Explorer 8, I receive an alert when the call is successful. However, this behavior does not occur in Firefox and Chrome. In other words, there is no alert disp ...

What is the process for mediating a SWF-Flash file with a PHP mediating, also known as an HTTP-Pseudostreaming script?

I am currently developing a mini context media platform that utilizes HTTP Pseudostreaming. This involves using a PHP script to manage the media file, ensuring proper access and linking to the correct directory. Below are the key components of my code: // ...

Having trouble setting a value for a textbox in angularjs

Greetings! I am currently working on a web application using AngularJS. My task involves binding data from various API's to a textbox in my project. Below is the snippet of the HTML code where I attempt to achieve this: <input class="with-icon" ty ...

Utilizing JavaScript variables imported from an external library in Next.js: A Guide

I am currently working on a Next.js with Typescript website and I am in the process of adding advertisements. The ad provider has given me instructions to embed this JavaScript code on my site: <script src="//m.servedby-buysellads.com/monetization. ...

Utilize JavaScript libraries in a TypeScript project

Looking to integrate a payment system called iyzico into my project. The iyzico payment library can be found here. However, there are no types available for it. How can I utilize this library in my Node.js TypeScript Express backend project? I attempted t ...

Prevent the loading of a <img> element and replace it with a new one using CSS

Is there a way to hide an <img> element without accessing the HTML directly, only by using CSS? The <img> element does not have any specific class. Here is the HTML markup: <img title="Manual" id="imgAjuda" src="images/ico_aj.png" width=" ...

Using percentages for sizing and margins in CSS

Looking to create a visually appealing page that always fills the entire screen? Check out this code snippet that does just that: #posts{ width:100%; height:auto; background:#666; } .entry{ float:left; margin-left: 4%; margin-top:10 ...