No jQuery or similar
The href that are stored in the link variable are images that are not found in the DOM
I want to save the values of the height and width of X number of images of different proportions with a for cycle, but the way I am doing it does not work (it generates zeros) since the image has not finished loading. This is what I wear:
var img = document.getElementsByClassName('post-image');
var link, w, h;
var margenes = [];
for(var i = 0; i < img.length; i++){
// La url de la imagen
link = img[i].parentElement.href;
// Agregar <img src="link"> al DOM, esto va dentro de un <div>
document.getElementById('thread').insertAdjacentHTML('afterbegin', '<div id="lightbox"><img id="lightbox-img" src="' + link + '"></div>');
// Obtener los valores de alto y ancho
var lightboxImg = document.getElementById('lightbox-img');
w = lightboxImg.width;
h = lightboxImg.height;
// Guardar una cadena de texto en el arreglo con los datos de alto y ancho
margenes.push("-" + h/2 + "px 0px 0px -" + w/2 + "px");
console.log(margenes[i]);
// Eliminar la imagen del DOM
document.getElementById('lightbox').parentNode.removeChild(document.getElementById('lightbox'));
}
The line
console.log(margenes[i]);
I generate -0px 0px 0px -0px
I want to save everything in the margins array because I use that string afterwards to add CSS. If there is a way to store in the h and w variables the height and width values before loading the image or in any other way that does not require the image to be DOM I ask you to let me know.