Marizona
Marizona

Reputation: 129

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

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

Upvotes: 3

Views: 1239

Answers (3)

GMKHussain
GMKHussain

Reputation: 4711

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>

Upvotes: 3

Sarun UK
Sarun UK

Reputation: 6756

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>

Upvotes: 1

Sergey
Sergey

Reputation: 1076

Here is the solution.

const div = document.querySelector('footer > div');

div.addEventListener('click', () => {
  const previousValue = Number.parseInt(div.innerText || 0);
  div.innerText = previousValue + 1;
});
footer div {
  width: 100px;
  height: 100px;
  background: #ccc;
}
<footer>
<div>
</div>
</footer>

Upvotes: 0

Related Questions