I want to run a time out function to show an image once the page is loaded but I don't know why it's not running. Is this a matter of syntax? Here's my code:
const screenshot = document.querySelector('#device-screenshot');
function loaded() {
console.log('loaded')
setTimeout(() => {screenshot.src = "dist/images/new-screenshot-2.jpeg"
}, 4000);
}
if (screenshot.complete) {
loaded()
} else {
screenshot.addEventListener('load', loaded)
screenshot.addEventListener('error', function() {
console.log('error')
})
}
CodePudding user response:
As I recall correctly, you don't need the curly braces in the setTimeout()
function. Normal syntax could be as follows:
function loaded() {
console.log('loaded')
setTimeout(() => screenshot.src = "dist/images/new-screenshot-2.jpeg", 4000);
}
If this doesn't work, then check to see if there is another way than .complete
to check if it is loaded. I have never seen nor used it, but this looks like correct usage and the loaded()
function should fire when the page loads. Alternatively, you can hook up an onload
attribute to the body
tag in the HTML file and set the value to 'loaded'
or another function instead of waiting for the image to load.
CodePudding user response:
What you are looking for is the onload
event, you would use it like so:
document.body.addEventListener("load", loaded);