Trying to access an array with onclick function

I am trying to apply an onclick function to an array of three elements, but setting the onclick property of the array does not work. Any ideas would be really helpful. Thanks!

Here is my code:

var btnArray = [
document.getElementById('buttonOne'),
document.getElementById('buttonTwo'),
document.getElementById('buttonThree'),
];
console.log(btnArray); 
btnArray.onclick = function revilImg() {
console.log('hey');
}

Upvotes: 0

Views: 508

Answers (2)

gyre
gyre

Reputation: 16777

Arrays don't have an onclick property. You need to iterate over it first (I have chosen to use Array#forEach), and attach the handler to each DOM element individually using addEventListener:

var buttons = [
  'buttonOne',
  'buttonTwo',
  'buttonThree'
].map(document.getElementById, document)

console.log(buttons)

function revealImage () {
  console.log('hey')
}

buttons.forEach(function (e) {
  e.addEventListener('click', revealImage)
})
<button id="buttonOne">#1</button>
<button id="buttonTwo">#2</button>
<button id="buttonThree">#3</button>

Upvotes: 2

Asons
Asons

Reputation: 87191

Add event listeners like this, where you loop through the array and add a handler to each object

var btnArray = [
  document.getElementById('buttonOne'),
  document.getElementById('buttonTwo'),
  document.getElementById('buttonThree'),
];

console.log(btnArray);

for (var i = 0; i < btnArray.length; i++){
  btnArray[i].addEventListener('click', function(){
    console.log('hey');
  })
}

If your buttons share a common class, i.e. mybuttons, you can use querySelecorAll()

var btnArray = document.querySelectorAll('.mybuttons');

console.log(btnArray);

for (var i = 0; i < btnArray.length; i++){
  btnArray[i].addEventListener('click', function(){
    console.log('hey');
  })
}

Upvotes: 1

Related Questions