On a mobile version of a webpage (really just if (window.innerWidth <= 1024){}
), I have a script to run a click() method on an element (a fullscreen icon) after the user clicks on an image.
It all works as expected when I have a setTimeout(()=>element.click()}, 600)
.
When I remove the timeout or set it to shorter wait times (100ms <= 500ms), it “works”, but the visuals aren’t correct.
I speculate something needs to load / run before the click() can be run, and I want to put an eventListener or another MutationObserve on it. But I can’t find any difference in document.body before and after the timeout. What am I missing here?
I uploaded a copy of the site here:
- https://purple-pattern.flywheelsites.com
- username / pass: flywheel /
flywheel
I’ve also included a screen recording showing it working and not working.
https://drive.google.com/file/d/12g3MoXIoUn64AM9_BLVDS4ahR4jAi2xO/view?usp=sharing
In the screen recording, look for:
- First load: all works as expected. Timeout is 700ms. Background is opaque. Image is clear.
- Next several loads: either the background is semi-transparent or the image is dark.
- Last load: all works as expected. Timeout is back to 700ms.
Thanks
"use strict";
console.log("sandbox js loaded");
// Loads lightbox images in fullscreen by default on mobile
const bsaPortfolioImg = document
.getElementsByClassName("fusion-image-carousel")[0]
.getElementsByTagName("img");
const bsaPortfolioImgFsBtn = document.getElementsByClassName(
"ilightbox-fullscreen"
);
console.log("bsaPortfolioImg: ", bsaPortfolioImg);
console.log("bsaPortfolioImg[0]: ", bsaPortfolioImg[0]);
console.log("bsaPortfolioImgFsBtn: ", bsaPortfolioImgFsBtn);
function bsaOnElementAvailable(selector, callback) {
const observer = new MutationObserver((mutations) => {
if (document.querySelector(selector)) {
observer.disconnect();
callback();
}
});
observer.observe(document.body, { childList: true, subtree: true });
}
if (window.innerWidth <= 1024) {
bsaOnElementAvailable(".ilightbox-fullscreen", () => {
console.log("element available!!");
// bsaPortfolioImgFsBtn[0].click();
console.log("document.body before Timeout: ", document.body);
setTimeout(() => {
console.log("document.body after Timeout: ", document.body);
bsaPortfolioImgFsBtn[0].click();
console.log("clicked");
}, 600);
});
}