0

Hi I'm trying to get a variable to increment by one when I click on any one of my divs.

this code works for if I click on the page or window in general:

var click = 0;
window.onclick = function () {
click++;

console.log(click);
}

but it has to only work for when I click on one of the 36 buttons inside a container.

I tried replacing "window" with my function that is connected to my div "buttons" but that didn't work.

an example of what I'm trying to do is:

var click = 0;
myFunction.onclick = function () {
click++;

console.log(click);
}

Here is my function:

var imgArray = [], []; 
function onClickCard(image)
{
image.src=imgArray[parseInt(image.name.substring(0, 1)) - 1]           [parseInt(image.name.substring(1, 2)) - 1];
}
user2825148
  • 21
  • 1
  • 6

2 Answers2

0
  1. Use jquery click function on element.
  2. If you do not want to use jquery, try this:

    document.onclick = function(event) { var target= event.target; if (target.nodeName == "BUTTON") { alert("button clicked"); } };

  3. Directly add on click inside the element definition as suggested above in comments.
A.G.
  • 734
  • 2
  • 8
  • 27
0

If you want to use plain Javascript, use this:

var click = 0;
window.onload = function () {
    var buttons = document.getElementById('container').querySelectorAll('div.button');
    console.log(buttons);
    for (i = 0; i < buttons.length; i++) {
        buttons[i].onclick = function () {
            click++;
            document.getElementById('result').innerHTML = click;
        }
    }
}

Demo here

In this demo I assumed you container has a ID #container, and your buttons are div elements with class .button.

Sergio
  • 28,539
  • 11
  • 85
  • 132