Using JavaScript, generate ten clickable circles on the screen. Each circle should display the number of times it has been clicked in the center when interacted with

I am currently working on my JavaScript skills and would like to implement a fun project involving 10 colorful circles. While I can easily create these circles using HTML and CSS, I require assistance with the interactive functionality using JavaScript. My goal is for each circle to display the number of times it has been clicked on. For instance, if I click on the blue circle three times, the number 3 should appear in the center of that circle.

    <style>
        .circle{
            border-radius: 50%;
            width: 40px;
            height: 40px;
            padding: 3px;
            background: blue;
            border: 2px solid black;
            text-align: center;
        }
    </style>
    
</head>
<body> 
    <div class="circle">
        3
    </div>
</body>

Answer №1

To start, you'll need to set up the circle divs as shown below:

<div class="circle" onclick="increment_circle(this);">0</div>

The onclick attribute plays a key role in triggering the script.

You should then create the JavaScript code like this:

<script>
function increment_circle(element) {
  var current = parseInt(element.innerHTML);
  current++;
  element.innerHTML = current;
}
</script>

I hope this explanation is helpful!

function incrementCircle(element) {
  var current = parseInt(element.innerHTML);
  current++;
  element.innerHTML = current;
}
.circle {
  border-radius: 50%;
  width: 40px;
  height: 40px;
  padding: 3px;
  background: blue;
  border: 2px solid black;
  text-align: center;
}
<body>
  <div class="circle" onclick="incrementCircle(this);" style="background-color:blue;">0</div>
  <div class="circle" onclick="incrementCircle(this);" style="background-color:red;">0</div>
  <div class="circle" onclick="incrementCircle(this);" style="background-color:green;">0</div>
  <div class="circle" onclick="incrementCircle(this);" style="background-color:orange;">0</div>
  <div class="circle" onclick="incrementCircle(this);" style="background-color:yellow;">0</div>
  <div class="circle" onclick="incrementCircle(this);" style="background-color:gray;">0</div>
</body>

Answer №2

Here is a different approach to solve the problem:

const circles = document.querySelectorAll(".circle");

const increaseNumber = function() {
  let previousNumber = +this.innerHTML || 0;
  this.innerHTML = previousNumber + 1;
};

circles.forEach(circle => {
  circle.addEventListener('click', increaseNumber);
});
.circle {
  border-radius: 50%;
  width: 40px;
  height: 40px;
  padding: 3px;
  background: blue;
  border: 2px solid black;
  text-align: center;
  float: left;
  margin-left: 5px;
}

.red {
  background: red;
}

.gray {
  background: gray;
}
<div class="circle">
  0
</div>

<div class="circle red">
  0
</div>

<div class="circle gray">
  0
</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

First experience with Django Bootstrap Modal Ajax was flawless, but on the second attempt, it was not as successful

I am currently utilizing Django 2.2 in conjunction with Bootstrap. The method implemented is as follows: Triggering the opening of a modal window, User updates the data, User saves the data, Underlying table from where the window originated is updated a ...

Utilizing JS Underscore for combining and organizing arrays with common keys

I am facing a scenario where I have two arrays: "array_one": [ { "id": 1, "name": One }, { "id": 2, "name": Two } ] "array_two": [ { "id": 1, "name": Uno }, { "id": 3, "name": Three ...

Determining the margin-left value of a centrally positioned table

I have a table with variable columns, meaning the columns of the table are dynamic. The number of columns will keep changing, causing the table to be centralized and the margin-left value to adjust accordingly. Now, I need to calculate the margin-left val ...

Discovering a specific element within a deeply nested JavaScript object

let data = [{ "ItemAID" : 1, "ItemADesc" : [ { "ItemBid" : 11, "ItemBDesc" : [ { "ItemCid" : 111, "ItemCTitle" : "TitleC111", }, { " ...

Troubleshooting a problem with the transition of the hamburger menu icon in SC

I'm encountering an issue with the transition property and attempting to utilize the all keyword. After including a fiddle, I can't seem to figure out if I've made a simple mistake or if there is something else going on. I have seen the all ...

Is there a bug in NodeJS that causes an error when a return statement is used with a line feed before the string to be returned?

I am attempting to call a function from a module in order to generate an HTML string. When the function is written with a line feed (LF) between the return statement and the string declaration as shown below, the return value becomes "undefined"... export ...

Getting data from a URL using Node.js and Express: A beginner's guide

Currently, I am facing an issue with extracting the token value from the URL http://localhost:3000/users/reset/e3b40d3e3550b35bc916a361d8487aefa30147c8. My get request successfully validates the token and redirects the user to a password reset screen. Howe ...

Encountering invalid JSON response while making an API request

Struggling to integrate GoToMeeting's API by sending a POST request to create a meeting. Currently, attempting to manually code the meeting body and send the necessary headers, but encountering an issue with invalid JSON error. Below is the code snipp ...

Retrieving pictures by their unique identification number

Utilizing a flexslider, I have set up an image display feature as shown in the JSFiddle link below. The slider has been optimized to dynamically extract images from a specific directory, where images are named with numbers like 1023, 2045, 304654, and so o ...

Troubleshooting problem with Materialize CSS in UI router

Incorporating Materialize CSS along with Angular's ui.router for state management and HTML rendering has led to a challenge. Specifically, the Materialize Select component is not initialized upon state changes since Materialize components are typicall ...

Can diverse array elements be divided into separate arrays based on their object type in JavaScript?

Looking to create new arrays based on objects with similar attributes from an existing array? Here's how: Starting with this [ {name: "test", place: "country"}, {name: "walkAndEat", Long: 100, Lat: 15, Location: "place name"}, {name: "te ...

Methods for retrieving a file within a nodejs project from another file

Currently, my project has the following structure and I am facing an issue while trying to access db.js from CategoryController.js. https://i.sstatic.net/8Yhaw.png The code snippet I have used is as follows: var db = require('./../routes/db'); ...

What is the reason behind the necessity for a React class component to always invoke super(props) within its constructor function?

I recently came across a tutorial from reactjs.org that mentioned the importance of calling the base constructor with props in class components. However, further research led me to a StackOverflow answer suggesting that super() can be used instead of super ...

Using AngularJS to update text content retrieved from a file and display it in a textarea

Is there a way to create a textarea using AngularJS that can be populated either by typing, entering a URL, or uploading a plain text file? While I am able to load the file content into the variable linked to the textarea, I'm facing an issue where ge ...

The switchView feature is currently malfunctioning and unable to access the content on the next page

For my application's admin panel design, I've divided my home into containers. The aim is to display details of clicked items in Images.html and Categories.html when a menu item in the 2nd container (also known as side bar) is clicked. However, m ...

What is the best way to handle AJAX responses in an onchange event

I'm working on a form where the select option in the input (jurusan) is automatically filled based on the selected value. I need to know how to change the value that appears after selecting an option. For example, if I select option A, it displays th ...

Issue with connecting the 'Enter' key to the button - no success

My current setup involves using jQuery to link the Enter key to an HTML button through this code snippet: $("#console").keyup(function(event){ if(event.keyCode == 13) { $("#submit").click(); } }); HTML: <input autocomplete="off" type= ...

What is the best way to change CSS style for a button when clicked using JavaScript?

Is there a way to switch the background style of a CSS div when clicking the same button? function changeBg() { var divElem = document.getElementById("change-bg"); if (divElem.style.backgroundColor === "yellow") { divElem.style.backgroundColor ...

When the span element's height is set to 100%, it does not automatically match the height of its parent div

I have a scenario where I am working with two div elements and a span element in between. The parent div element does not have a defined height, it is calculated based on the content within the div. However, the span element's height is set to 100% ev ...

Ways to use jQuery to disable row form elements in the second and third columns

I need a way to deactivate form elements in the second and third columns, starting from the second row until the nth row using a jQuery selector. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/> ...