Adding eventListener to all items in prepopulated array

Hi,

I’m new to JavaScript and I was wondering if anyone could help me.

I’m trying to add an eventListener to all items of a prepopulated array. Basically while clicking on 1 item in 1 array, I want to toggle the visibility of the item in the other array that corresponds with the item clicked in the first array.

I.e.

array1 = [1,2,3,4]
array2 = [a,b,c,d]

I want all the items in the 2nd array hidden but when say item 1 in the first array is clicked, a in array2 will have its visibility toggle from hidden to visible, then when item 1 is clicked again it will toggle back from visible to hidden.

Any help would be greatly appreciated! Thank you in advance!

You can’t add event listeners to an array itself. It has to be done on your user interface (UI)… either your radio button group, dropdown list, list box etc. When you do that you add an event listener to the UI component itself which usually contains the ID or index of the item you are currently clicking on. This ID will then be passed to the other array to retrieve the appropriate value.

Perhaps you could make a sample of what you want with the UI and post it here?

// setup
var arr1 = []
for (var i = 0; i < 6; i++){
    var e = document.createElement('button')
    e.innerHTML = String.fromCharCode(97 + i)
    document.body.appendChild(e);
    arr1.push(e)
}

var arr2 = arr1.splice(3, 3)

// what katsusauce wants to happen
arr2.forEach(function(e){
    e.style.visibility = 'hidden'
})
arr1.forEach(function(e, i){
    e.addEventListener('click', function() {
        arr2[i].style.visibility = arr2[i].style.visibility == 'hidden' ? '' : 'hidden'
    })
})
1 Like

Hey krilnon, thanks for posting that. I learned something new =)

No problem. What’d you learn?

I learned a new way to use the forEach method in Arrays =) Didn’t occur to me to solve it in this way. Your solution is elegant and simple… especially passing the i value to the buttons in the arr1