ThisNameWasTaken ThisNameWasTaken - 3 years ago 84
Javascript Question

Add click count inside an object inside an array

im trying to count the clicks that an user do in each image, the click count is stored in an object, inside an array. how i can do this?

var clicks = 0;
var gatas = [];

gatas[0]= {img : "img/ml.jpg", clicks : 0};
gatas[1]= {img : "img/ma.jpg", clicks : 0};

for (var i = 0; i < gatas.length; i++) {

var elemImg = document.createElement("img");
elemImg.src = gatas[i].img;

var elemClick = document.createElement("h3");

//ADD +1 every time the user clicks an image, storing the count in the
//object

elemClick.textContent = gatas[i].clicks;

document.body.appendChild(elemClick;
document.body.appendChild(elemPic);

};

Answer Source

You have to bind a click event handler for every image.

Also, don't forget to use let keyword in order to declares a block scope local variable.

Variables declared by let have as their scope the block in which they are defined, as well as in any contained sub-blocks. In this way, let works very much like var. The main difference is that the scope of a var variable is the entire enclosing function.

This is a problem found usually in closures.

var clicks = 0;
var gatas = [];

gatas[0]= {img : "img/ml.jpg", clicks : 0};
gatas[1]= {img : "img/ma.jpg", clicks : 0};
let elemImg=[];
let elemClick=[];
for (let i = 0; i < gatas.length; i++) {
    elemImg[i] = document.createElement("img");
    elemImg[i].src = gatas[i].img;
    elemClick[i] = document.createElement("h3");
    elemClick[i].textContent = gatas[i].clicks;
    elemImg[i].onclick=function(){
      gatas[i].clicks++;
      elemClick[i].textContent = gatas[i].clicks;
    };
    document.body.appendChild(elemClick[i]);
    document.body.appendChild(elemImg[i]);
};

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download