0

I may be overlooking something obvious but this just doesn't seem to go right.

I have this little code block in which an addEventListener method should trigger a function and meanwhile pass a parameter through so I can work with different functions while creating all EventListeners with one loop. It does work, but the function gets invoked immediately when the site finishes loading.

Why doesn't the function wait until it gets triggered, but runs immediately?

var html = document.getElementsByTagName('html');
var pics = document.getElementsByClassName('pics');
var functions = [];

for(h=0;h<pics.length;h++){
    array[h] = show(h);
}

for(p=0;p<pics.length;p++){
    pics[p].addEventListener('click',array[p]);
}

function show(index){
    html[0].style.backgroundColor = "black";
}
RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53
KevDev
  • 150
  • 1
  • 1
  • 8

2 Answers2

3

In the script

for (h = 0; h < pics.length; h++) {
    array[h] = show(h);
  }

you are calling the function show with value of h.

Its invoked at that time.So,background get setup with given color.

Its not because of addEventListener you are adding in the second for loop

You can write in this way.

for (h = 0; h < pics.length; h++) {
    array[h] = show; // don't  call,store the function reference
  }

  for (p = 0; p < pics.length; p++) {
    pics[p].addEventListener('click', array[p].bind(this,p));
  }

You can shorten two for loop into one

  for (p = 0; p < pics.length; p++) {
    pics[p].addEventListener('click', show.bind(this,p));
  }

Note :

addEventListener expect callback and not an function call.

RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53
  • It works, thanks for your help! could you explain the .bind method to me in some easy words? i dont quite get how it works, even after researching it on the Internet. greetz! – KevDev Apr 02 '17 at 06:11
0

array[h] = show(h); is being invoked on page load. Here is working code.

var html = document.getElementsByTagName('html');
var pics = document.getElementsByClassName('pics');
var functions = [];
var array = [];

for(h=0;h<pics.length;h++){
  array[h] = function () { show(h) };
}

for(p=0;p<pics.length;p++){
  pics[p].addEventListener('click',array[p]);
}

function show(index){
  html[0].style.backgroundColor = "black";
}
loelsonk
  • 3,570
  • 2
  • 16
  • 23