Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

change color of a box in a grid when clicked

I wonder if it’s possible to change the color of a box when it’s beeing pressed.

I’m trying to code a "calculator layout" and want to start with do this part

1 2 3
4 5 6
7 8 9
  0

This is what i’ve been working with and stuck with.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$(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>

>Solution :

It looks like you’re on the right track! However, there are a few adjustments needed in your JavaScript code. Here’s the corrected version of your JavaScript code to change the color of a box when it’s clicked:

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

In this code, $(this) refers to the element that was clicked, and .css(‘background-color’, ‘red’) is used to change the background color of that element to red when it’s clicked.

You can apply the same approach to the other boxes as well. For example, if you want to change the color of the box with id k2 to blue when it’s clicked, you can add the following code:

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

You can repeat this pattern for the other boxes as needed to change their background colors when clicked.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading