FKa
FKa

Reputation: 47

onClick on loop elements

I need to add onClick event to loop elements:

<div id="try"><div/>
<div id="boxes"><div/>

<script>

var x=1;
var boxes=[];
while(x<=7){
boxes[x++]=['<div class="colorbox">whatever now, because it will be  colored boxes</div>'];}
document.getElementById("boxes").innerHTML=boxes;

var i = document.getElementsByClassName('colorbox');
document.write(i);
i.onclick = function(){doit(1, 2);}

function doit(a, b){
    document.getElementById("try").innerHTML=a + b;}
<script>

I don't know why onclick event doesn't work in this example. Console doesn't give any mistakes. What could be wrong? 'document.write(i)' shows, that var i is nor empty nither undefinited. It's just html object.

Upvotes: 1

Views: 996

Answers (2)

Alex McMillan
Alex McMillan

Reputation: 17952

document.getElementsByClassName() uses the plural "Elements" and hence returns a collection. If there is only a single element that matches the class selector, it will return a collection with one element.

Hence, you need to attach your handler to the element itself, rather than the entire array. As you've tagged your question jQuery, I'd suggest using jQuery (which will attach the handler to each element in the array):

var x=1;
var boxes=[];
while(x <= 7) {
    boxes[x++] = ['<div class="colorbox">whatever now, because it will be  colored boxes</div>'];
}

document.getElementById("boxes").innerHTML = boxes;

var i = document.getElementsByClassName('colorbox');

document.write(i);

$(i).on('click', function () {
  doit(1, 2);
});

function doit (a, b) {
    document.getElementById("try").innerHTML = a + b;
}

Upvotes: 2

FKa
FKa

Reputation: 47

It works when I use $('.colorbox') instead of $(i), remove all parts with i variable and change .on event to .click event:

var x=1;
var boxes=[];
while(x<=7){
boxes[x++]=['<div class="colorbox">whatever now, because it`ll be colored boxes</div>'];}
document.getElementById("boxes").innerHTML=boxes;

$('.colorbox').click(function () {
  doit(1, 2);
});

function doit(a, b){
    document.getElementById("try").innerHTML=a + b;}

Upvotes: 0

Related Questions