I have some text strings stored in an array and I want to use them to add a CSS property to a series of images.
var img = document.getElementsByClassName("post-image");
var link, w, h;
var margenes = [];
for (var i = 0; i < img.length; i++) {
// Obtener la url de las imágenes externas al DOM
link = img[i].parentElement.href;
// Insertar una <img src="link"> en el DOM
document.getElementById("thread").insertAdjacentHTML("afterbegin", "<div id='lightbox'><img id='lightbox-img' src='" + link + "'></div>");
// Utilizar las variables h, w para almacenar el alto y ancho de la imagen
var lightboxImg = document.getElementById("lightbox-img");
w = lightboxImg.width;
h = lightboxImg.height;
// Construir una cadena de texto con los valores de h y w para mandarla al arreglo
margenes.push("-" + Math.floor(h / 2) + "px 0px 0px -" + Math.floor(w / 2) + "px");
// Eliminar la imagen del DOM
document.getElementById("lightbox").parentNode.removeChild(document.getElementById("lightbox"));
}
for (var i = 0; i < img.length; i++) {
// Comprobar que imprime la cadena de manera adecuada
console.log("Prueba " + margenes[i]);
}
for (var i = 0; i < img.length; i++) {
// Cuando el puntero está sobre una de las imágenes
// no son las mismas que el ciclo for anterior
img[i].addEventListener("mouseover", function () {
link = this.parentElement.href;
document.getElementById("thread").insertAdjacentHTML("afterbegin", "<div id='lightbox'><img id='lightbox-img' src='" + link + "'></div>");
var lightboxImg = document.getElementById("lightbox-img");
// No funciona
lightboxImg.style.margin = margenes[i];
// Imprime "Valor: undefined"
console.log("Valor: " + margenes[i]);
}, false);
img[i].addEventListener("mouseout", function () {
document.getElementById("lightbox").parentNode.removeChild(document.getElementById("lightbox"));
}, false);
}
My question is why in the third cycle for
that string appears as undefined
?
I have tried the following, but it is not a solution to the problem either:
String(margenes[i]);