Click to fill a CSS square using JavaScript

I am currently in the process of creating a simple habit tracker using html, css, and javascript. The design includes red squares filled with white created using div elements, and they are positioned within a container to ensure consistent spacing even when the page is resized.

My goal is to enable users to click on a square to fill it and then click again to unfilled it. However, I am facing an issue where nothing happens when I try to interact with the squares.

In addition, I am concerned that the current setup may not allow for individual addressing of each square as intended. If anyone has suggestions or pointers on how to address this specific concern, I would greatly appreciate it.

The code for my project is provided below, but you can also access a live version on Codepen:

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>

Answer №1

function ToggleColor(e) {
  e.classList.toggle('red');
}
.color-container {
  border: 10px solid black;
  display: flex;
  justify-content: space-between;
}

.color-container div {
  width: 50px;
  height: 50px;
  background: white;
  border: 10px solid red;
}
.color-container div.red {
  background:red;
}
<div class="color-container">
  <div onClick="ToggleColor(this)"></div>
  <div onClick="ToggleColor(this)"></div>
  <div onClick="ToggleColor(this)"></div>
  <div onClick="ToggleColor(this)"></div>
</div>

Answer №2

There are various methods to achieve this task, but in general, it is recommended to utilize CSS for styling and javascript for toggling a class.

For instance, using CSS:

.active-square {
    background: red
}

Then in the HTML, you can implement:

<div onclick="this.classList.toggle('active-square')">My Square</div>

Typically, direct use of click handlers like this is discouraged, and it's better to set up with javascript. However, this serves as a basic example of how it can be done.

Answer №3

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

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

The process of displaying a single large image from a local file system using the elements input, img, and canvas

I am attempting to create a mobile-friendly picture upload webpage, but I keep experiencing memory issues causing the browser to crash when the picture is too large. Here's my code: <input type="file" id="testFile" /> <img src="" style="posi ...

Implementing JavaScript validation to alter the background image

I encountered a small issue while working on my project. I was designing a form in HTML using JavaScript, and for the input fields, I decided to use a background image with padding on the left to enhance its appearance. Everything seemed fine until I ran i ...

JavaScript Tab Fade Effect

I have a tab system that utilizes JavaScript to switch tabs. I am trying to implement a fade in and out effect when switching tabs. The current JavaScript simply adds or removes the clicked tab selected by the user. I have managed to partially achieve the ...

The ActivatedRoute.routeConfig object appears to be empty in an Angular 2 project built with Angular-cli

Two projects I've created using angular-cli are working perfectly fine. However, in one of them, the routeConfig is showing as null and I can't figure out what's causing this issue. Both projects have identical package.json files, so there ...

Unexpected results occurring during JavaScript refactoring process

Having this repetitive code snippet that switches between two radio buttons being checked within my $(document).ready(): $(document).ready(function () { $("#New").click(function () { var toggleOn = $("#New"); var tog ...

Prevent parent from scrolling when hovering over a div in HTML5

Unfortunately, the scrolling attribute is not supported in HTML5. I'm facing an issue where I have an svg inside an iframe within a div, and I need to enable scroll functionality within the div while preventing the page from scrolling at the same time ...

Angular Application error: Unable to find function smartContract.at

While working on my Angular Dapp, I encountered an error in the first block of code stating "smartContract.at is not a function". settingMap(hashRoot : string) { var smartContract = new window.web3.eth.Contract([contractAbi]) var contract = smartContr ...

Troubleshooting a navigation problem with DNN and Bootstrap-3 specifically for mobile devices

Here are the steps to demonstrate this issue: 1. Visit the following page of the website: 2. Resize your browser window to mobile size and close the menu using the icon. After the animation finishes, the navigation items reappear. I have been struggling ...

Only by refreshing can submission be prevented effectively

My website has a page that redirects to another page. On the second page, I have prevented the default form submission and implemented my own custom functionality using the following code: <!DOCTYPE html> <html> <head> <ti ...

What is the process for incorporating markers from a JSON file into a PHP webpage using AJAX?

My goal is to display markers on a PHP page using the Google Maps API controlled by radio buttons. All marker data is loading correctly (via JSON), but the map itself is not rendering. I have checked for script exceptions in the console and the run() met ...

Determining the height of the error container using jQuery validate

I am having difficulty retrieving the height of the error container when using the 'jquery validate' plugin to submit a form with errors. The height value of the error container is not displaying and the alert box is not working. Can someone prov ...

Carousel malfunctioning, refusing to slide smoothly

I recently copied the bootstrap 5 Carousel code and tweaked it with some additions, however, it's not functioning correctly. It seems to only go to the 2nd slide and then stops. Strangely enough, when I open the developer tools (F12) and go to inspect ...

Verify if a particular property exists on the element's parent

There is a button with the following attributes <button data-cart-itemid="1be8718a-6993-4036-b7c6-8579e342675d" data-action="inc"> My goal is to determine if the click event occurred on this button specifically, by checking the a ...

What is the best way to display multiple Google Charts using various data tables within a single PHP document?

I am looking to create multiple charts using data from different sources. The data comes from queries within a PHP file named ajax.php. Below is the code snippet: //JOB POST BY SALARY function jobsalary(){ // Function logic here... } //JOB POST BY J ...

Creating a paragraph from text inputs using React

I'm currently working on code that retrieves input from two textboxes - one for a string value and one for a number value. I want this data to be displayed in real-time within a paragraph without the need for a submit button. I've been struggling ...

Encountering a module injection error in AngularJS related to the ui.grid feature during my first experience with it

Trying to develop an AngularJS app, encountering the following error upon running the code: Uncaught Error: [$injector:modulerr] Failed to create module myApp: Error: [$injector:modulerr] Failed to create module ui.grid: Error: [$injector:nomod] Module &a ...

Change wiki text into HTML using Python for showcasing on a webpage

Despite trying various tools for 6 hours, I have been unable to find one that can properly interpret wikitext like the example below: '<center>Welcome to the world's foremost open content<br><big><big><big>'&ap ...

Learn how to dynamically swap background images in Vue.js when hovering over different elements

I am facing an issue where I need to change a background image upon hovering over four different elements, with one unique image for each element. Here is what I have attempted: HTML: <div class="projects"> <a v-on:mouseover="hover=myimage1" ...

Checking if multiple text fields with identical names are valid using BootstrapValidator

I'm facing an issue where I am unable to validate multiple text fields with the same name. The validation only works for the first input text field, but not for the rest. <form id = "frm_org_id"> <input type="text" name="email_address[]" pla ...

Show Hindi content in Android web browser

I am currently developing an application that requires displaying Hindi text in an HTML format. I need to display an entire HTML page with content in Hindi. Can someone assist me with this? Any help would be greatly appreciated. Here is a snippet of my cod ...