admin管理员组文章数量:1416050
I am creating a basic website for a personal project. I have a div element in the code as well. When a user clicks this particular div element, I want the site to display a counter next to the div element to count how many times it has been clicked. I don't need to save anywhere else how many times it has been clicked. Is this possible with JS and how could I do this?
I don't know much Javascript at all, so I haven't known what exactly to try.
I want to have a basic counter next to the element to count how many times it has been counted. Again, nothing needs to be saved a server. Also, I am not worried about how many times a user can click the div element and add another number.
I am creating a basic website for a personal project. I have a div element in the code as well. When a user clicks this particular div element, I want the site to display a counter next to the div element to count how many times it has been clicked. I don't need to save anywhere else how many times it has been clicked. Is this possible with JS and how could I do this?
I don't know much Javascript at all, so I haven't known what exactly to try.
I want to have a basic counter next to the element to count how many times it has been counted. Again, nothing needs to be saved a server. Also, I am not worried about how many times a user can click the div element and add another number.
Share Improve this question asked May 12, 2019 at 1:01 Gabrielle Lucies-YantisGabrielle Lucies-Yantis 411 silver badge6 bronze badges6 Answers
Reset to default 2First you need a counter where you store the number of clicks
let clicks = 0;
Then you need to find your div in the DOM using
document.getElementById() // or
document.getElemenyByClass() // or similar
An example of finding your div would be
my_div = document.getElementById("click_div");
Then you need to add an Event listener to the div
Something like this
my_div.addEventListener("click", function(){
// add code here that increases the /clicks/ variable
});
Wele to stackoverflow @Gabrielle! I understand that your new to JavaScript and haven't been able to find a meaningful answer to attempt this project.
Lets start basic first, in JavaScript, we need to store the value of clicks, so we declare a variable
i = 0
Now we want to give that specific div an ID, so lets say <div id="special"> Some Content...</div>
Within our JavaScript code block, we need to reference to special, so we create another variable,
myDiv = document.getElementById("special")
myDiv
now is referenced to that special div you want to track. Next we create the on click event to track clicks on that element.
myDiv.addEventListener("click",function(){ Clicked! Do something... })
addEventListener
tells the DOM that it wants to listen to clicks occurring onto that element only and if so, trigger the instructions inside of the function tag.
Now we increase the counter, or the variable i
each time a click occurs, so we use
i += 1
This way each click that occurs, i
adds one to itself.
Lastly we have to show that number to another special ID on the page, I will leave that part "Since its simple" to you to figure out but I will reference it below.
// Variables
i = 0;
myDiv = document.getElementById("special");
// Event Listeners
myDiv.addEventListener("click", function() {
i += 1;
console.log(i);
});
<div id="special">Click Me!</div>
Some help with displaying the number inside of your page, go to JS Inner HTML
Hope this helped! Don't forget to thumbs this up if it did!
I’ve created a div and filled it with a colour to make it easily distinguishable. Clicking on the div will produce a pop-up where the count increments with each click.
<!DOCTYPE html>
<html>
<style>
div {
width: 500px;
height: 100px;
border: 1px solid grey;
background-color: blue;
}
</style>
<head> </head>
<body>
<script>
let count = 0;
function counter() {
count = count + 1;
alert(count);
}
</script>
<div onclick="counter()"> </div>
</body>
</html>
Do you mean a basic counter like this? You can also add the eventlistener to a normal div (doesn't need to be a button element):
JS:
$(document).ready(function() {
let counter = 0
document.getElementById("button").addEventListener("click", function(){
counter++
document.querySelector(".counter").innerHTML = counter
});
});
HTML:
<button id="button">Click!</button>
<div class="counter">0</div>
First, you need to give your divs labels that javascript can target. We can use id
because they are unique. For example:
<div id="clicker"></div>
The way javascript targets id
is via document.getElementById("clicker")
Next, we need to know when the div is being clicked. We do this by attaching a "listener" to the div that tracks "clicks":
document.getElementById("clicker").addEventListener("click", ...
Now, when a click is detected, that the function (i.e. code) that is attached to the click will run. The following explains the code in the function.
We use .textContent
to retrieve the text content in the div, and assign it to the variable count
:
let count = document.getElementById("counter").textContent;
Since count is a string, we convert it to numbers first with the parseInt
function. Not all the time necessary in javascript as it automatically coverts, but good practice anyhow.
parseInt(count);
Now that we know it's a number, we can add one to it. This is a short form:
counter++; // same as saying counter = counter + 1;
Remember how we got the text content from the div with .textContent
? We can also set the text content with the same .textContent
like so:
document.getElementById("counter").textContent = count; //set to new value
Putting it together:
// target the "clicker" div and adds a listener to detect clicks
document.getElementById("clicker").addEventListener("click", function (event) { // for each click, it will run this function
// get current value from "counter" div
let count = document.getElementById("counter").textContent;
// turn string to integer
parseInt(count);
// add one
count++;
// set the new value back to "counter" div
document.getElementById("counter").textContent = count;
});
div {
display: inline-block;
padding: 5px;
border: solid 1px gray;
}
<div id="clicker">click here</div><div id="counter">0</div>
Here's a very beginner-friendly way to do it:
HTML and CSS:
The HTML contains two div
elements (each with its own id
attribute so our JavaScript code can easily find them.) And the CSS improves the appearance of the HTML.
JavaScript:
Two variables are created, and each one stores a reference to one of the div
elements.
An event listener is created, to notice whenever a click
event happens on the page and respond by calling the count
function.
The count
function is created. Most of its statements are wrapped inside an if
block, so that the code will only execute if the condition is met. (The triggering condition is that the target of the click
event was the div element whose id
attribute has the value "clickableDiv
".)
Now whenever a click happens, if the condition is met, the rest of the code runs:
- Two variables are created:
oldCount
andnewCount
. oldCount
is assigned a value. (That value is the output of calling the built-inparseInt()
function, using whatever is inside thecounterDiv
element as the input.newCount
is assigned a value. (That value is one more than the value inoldCount
.)- Whatever is inside the
counterDiv
element is replaced with the value stored innewCount
.
// Defines references to elements (using `const` because the values
// should never change)
const clickableDiv = document.getElementById("clickableDiv");
const counterDiv = document.getElementById("counterDiv");
// Defines a listener that will call our function whenever a click happens
document.addEventListener("click", count);
// Defines the `count` function
function count(event){
// Limits which click events will change our counter
if (event.target == clickableDiv){
// Declares variables to hold numbers (using `let` in case we
// might want to change the values later)
let oldCount;
let newCount;
// Assumes the HTML content of counterDiv looks like a number,
// gets that number, and stores it in oldCount
oldCount = parseInt(counterDiv.innerHTML);
// Adds 1 to the number stored in oldCount, and stores the result
// in newCount
newCount = oldCount + 1;
// Makes a string from the number (not strictly necessary)
// and replaces the HTML content of counterDiv with that string
counterDiv.innerHTML = newCount.toString();
}
}
div {
float: left;
width: 25%;
height: 2em;
padding: 1em;
text-align: center;
font-weight: bold;
border: 1px solid grey;
}
<div id=clickableDiv>Click me</div>
<div id="counterDiv">0</div>
本文标签: javascriptHow do I add a counter to show how many times a div element has been clickedStack Overflow
版权声明:本文标题:javascript - How do I add a counter to show how many times a div element has been clicked? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745247187a2649608.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论