I'm having some issues with some JavaScript code. What I am trying to do is add event listeners to elements in an array.
The problem is that after the code is ran only the last element in the array gets the eventlistener working, the rest of the elements are returning errors.
I'm assuming this is because of the logic I'm using with the for loop and the eventlisteners. What would be an effective way to achieve the desired result?
function addSlider(config) {
var controls = `
<div id="next"> next </div>
<div id="previous"> previous </div>`;
var S_wrapper = config.wrapper;
var controls_html = document.createElement("div");
controls_html.setAttribute("id", "ctrl");
controls_html.innerHTML = controls;
var arrayData = config.wrapper.split(",");
for (i = 0; i < arrayData.length; i++) {
(function(index) {
document.querySelector(arrayData[i]).appendChild(controls_html);
var parent = document.querySelector(arrayData[index]);
console.log(i, index, arrayData[index], parent);
document.querySelector(arrayData[index]).addEventListener("mouseover", function(){
this.querySelector("#ctrl").style.display = "block";
})
document.querySelector(arrayData[index]).addEventListener("mouseout", function(){
this.querySelector("#ctrl").style.display = "none";
})
})(i);
}
}