Reputation: 87
I am prototyping a basic habit tracker in html, css and javascript. There are some outlines of red squares (filled white) which are made using divs. These squares are then placed within a container to maintain equal spacing even if the page is resized.
I am trying to allow the user to click a square to fill it in and then be able to click it again to unfill it. When I click on the squares nothing happens.
Another problem I can foresee is that the squares may not be individually addressable in the way that I have it written and I'm not exactly sure how to solve that so if someone could give some pointers on how to do that, that would be nice.
All my code is provided below but here is also a codepen link if anyone is interested:
https://codepen.io/CPU_Coding/pen/wvzaWMb
function FillSquare() {
document.getElementsByClassName('eqi-container div')[0]
.addEventListener('click', function (event) {
document.body.style.backgroundColor = 'red';
});
}
.eqi-container {
border: 10px solid black;
display: flex;
justify-content: space-between;
}
.eqi-container div {
width: 50px;
height: 50px;
background: white;
border: 10px solid red;
}
<h2>Square Clicker</h2>
<div class="eqi-container">
<div onClick="FillSquare"></div>
<div onClick="FillSquare"></div>
<div onClick="FillSquare"></div>
<div onClick="FillSquare"></div>
</div>
Upvotes: 1
Views: 878
Reputation: 51
$(function(){
$('.eqi-container div').click(function(){
$(this).toggleClass('fill');
})
})
.eqi-container {
border: 10px solid black;
display: flex;
justify-content: space-between;
}
.eqi-container div {
width: 50px;
height: 50px;
border: 10px solid red;
}
.fill{
background:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>Square Clicker</h2>
<div class="eqi-container">
<body>
<div ></div>
<div ></div>
<div ></div>
<div></div>
</div>
Upvotes: 0
Reputation: 9142
There are many ways to do this, but generally, you should think about using CSS for the styling, and javascript to toggle a class.
For example, in CSS:
.active-square {
background: red
}
Then in the HTML, you could do:
<div onclick="this.classList.toggle('active-square')">My Square</div>
Generally you would not directly use click handlers like this, and would set things up with javascript. But this is a basic example of how it can work.
Upvotes: 0
Reputation: 85
function FillSquare(e) {
e.classList.toggle('red');
}
.eqi-container {
border: 10px solid black;
display: flex;
justify-content: space-between;
}
.eqi-container div {
width: 50px;
height: 50px;
background: white;
border: 10px solid red;
}
.eqi-container div.red {
background:red;
}
<div class="eqi-container">
<div onClick="FillSquare(this)"></div>
<div onClick="FillSquare(this)"></div>
<div onClick="FillSquare(this)"></div>
<div onClick="FillSquare(this)"></div>
</div>
Upvotes: 3