I try to sort Images by landscape/portrait format therefor I first select all images on the page with the selectFunction() then I sort them with the function "hochquer" which triggers further actions.
my Problem: One image shows up with a width and height of 0 in console.log() even though it is properly displayed on my page and has a actual width and height. If I reload the Page for a second time it works perfectly fine and I get a width and height for this Image.
can anyone help me with this?
//Screenshot of the console added
function selectFunction() {
img = document.querySelectorAll(".img");
let imgSelector = Array.from(img);
if (imgSelector % 2 != 0) {
imgSelector.push("even'er");
}
return imgSelector;
}
function hochquer(callback) {
for (let i = 0; i < selectFunction().length; i++) {
console.log(selectFunction()[i]);
let Width = selectFunction()[i].naturalWidth;
console.log(Width, "w");
let Height = selectFunction()[i].naturalHeight;
console.log(Height, "h");
let Ratio = Width / Height;
if (Ratio >= 1) {
//quer
querFormat.push(selectFunction()[i]);
} else {
querFormat.push(undefined);
}
if (Ratio < 1) {
//hoch
hochFormat.push(selectFunction()[i]);
} else {
hochFormat.push(undefined);
}
}
callback();
}
Update:
Screenshot of the console: [1]: https://i.stack.imgur.com/Jr6P8.png
some more code I use which I think addresses what @54ka mentioned
function newImg() {
let createImg = [];
let imgSrc = [];
const imgContainer = document.querySelector(".gallery");
for (let i = 0; i < Gallery.length; i++) {
createImg.push(new Image());
imgSrc.push(Pfad + Gallery[i]);
createImg[i].setAttribute("src", imgSrc[i]);
createImg[i].setAttribute("class", "Img");
imgContainer.appendChild(createImg[i]);
function checkImage(path) {
return new Promise((resolve) => {
createImg[i].onload = () => resolve({ path, status: "ok" });
createImg[i].onerror = () => resolve({ path, status: "error" });
});
}
loadImg = function (...path) {
return Promise.all(path.map(checkImage));
};
}
loadImg(imgSrc).then(function (result) {
console.log(result);
hochquer(sort);
});
}
newImg();