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];
}
3
  • you need to put the call to onclick inside of the div as one of its attributes. <div onclick="myfunction()"> </div> Commented Sep 28, 2013 at 1:45
  • See here: stackoverflow.com/questions/3495679/… Commented Sep 28, 2013 at 2:02
  • @harmonickey, don't suggest inline script please. Better with a click handler. Commented Sep 28, 2013 at 7:03

2 Answers 2

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.
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.