TransWikia.com

How to make a script in javascript that counts the total number of divs clicked

Stack Overflow Asked on November 15, 2021

Like the title says, I’m trying to make a function in Javascript that counts how many divs are clicked A N D tell me which ones were clicked For example:

<div>
 <div onclick="somefunction">1</div>
 <div onclick="somefunction">2</div>
 <div onclick="somefunction">3</div>
 <div onclick="somefunction">4</div>
</div>

Let’s say div 1 and 2 are clicked, how do I make a javascript function that will tell me which divs were clicked (in our case 1 and 2 were) and total number of divs that were clicked?

2 Answers

To keep track of the amount of clicks, I would declare a public variable that keeps track of the click count and have the function increment it each time it is called.

To check which div is clicked, I would pass the number of the div as a parameter.

HTML:

<div onclick="someFunction(1)"> 1 </div>
<br>
<div onclick="someFunction(2)"> 2 </div>
<br>
<div onclick="someFunction(3)"> 3 </div>
<br>
<div onclick="someFunction(4)"> 4 </div>

Javascript:

    var clickCount = 0;
    
    function someFunction(divNum)
    {   
        ++clickCount;
        console.log("Clicks: " + clickCount);
        
        switch (divNum)
        {
        case 1:
            console.log("Clicked: " + 1);
            break;
            
        case 2:
            console.log("Clicked: " + 2);
            break;
            
        case 3:
            console.log("Clicked: " + 3);
            break;
            
        case 4:
            console.log("Clicked: " + 4);
            break;
        }
    }
    

Answered by finndg on November 15, 2021

var divsClicked="divs clicked = ";
var count = 0;
display=document.getElementById('display');
function somefunction(num){
divsClicked = divsClicked + num + ",";
count++;
display.innerHTML=divsClicked + "count =" + count;
}
<div>
 <div onclick="somefunction(1)">1</div>
 <div onclick="somefunction(2)">2</div>
 <div onclick="somefunction(3)">3</div>
 <div onclick="somefunction(4)">4</div>
</div>
<div id='display'><div>

Answered by DCR on November 15, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP