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.
$(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>
2
Answers
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:
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:
You can repeat this pattern for the other boxes as needed to change their background colors when clicked.
No need for multiple different IDs and classes. You can use the same class to achieve your goal.
As per my suggestion, you need to make the previous one un-highlighted when any other box get clicked.
Working example below:
In case you want a different colors for different boxes then use
data-attributes