Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to count clicks on an element other than a button?

Tags:

javascript

I have an empty box in the footer section, which is situated in the div

<footer>
<div>
</div>
</footer>

I would like to write a function in javascript that would count the number of clicks in the div, and display the number of clicks in the same div. I am wondering how to achieve this without touching the html. I have seen how to achieve this with a button, but how can I achieve this with a div ? thanks

like image 853
Marizona Avatar asked Dec 14 '25 07:12

Marizona


2 Answers

Use .querySelector, if you dont to want add any ID or Class.

var elem = document.querySelector('footer div');

let countClicks = 0;

elem.onclick = function() { 
  countClicks++;
  elem.textContent = countClicks
};
div {
padding:10px;
background: #339900; 
color: #fff;
font-size: 44px;
}
<footer>
  <div></div>
</footer>
like image 99
GMKHussain Avatar answered Dec 16 '25 21:12

GMKHussain


var root = document.getElementById('root');

root.onclick = function() { 
var elem = document.getElementById('count');
  elem.innerHTML = +elem.innerText + 1;
};
#count {
font-size: 40px;
font-weight: bold;
}
<footer>
  <div id="root">Click HERE</div>
  <div id="count"></div>
</footer>
like image 37
Sarun UK Avatar answered Dec 16 '25 22:12

Sarun UK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!