I have a page function that shows and hides images every 5 seconds.
Instead of these two images, I need to open random images from the list each time.
I added an array with images, tried to add the creation of an image in the popup() function, and the removal of the hidePopup() function, but nothing happened.
var images = new Array("http://dummyimage.com/100x100/100/fff",
"http://dummyimage.com/100x100/304/fff",
"http://dummyimage.com/100x100/508/fff",
"http://dummyimage.com/100x100/70B/fff",
"http://dummyimage.com/100x100/90F/fff",
"http://dummyimage.com/100x100/AA0/fff",
"http://dummyimage.com/100x100/CB0/fff",
"http://dummyimage.com/100x100/EC0/fff");
var randomImage = Math.floor(Math.random() * images.length);
popup();
function popup() {
document.getElementById("disclaimer").style.display = "block";
setTimeout(hidePopup, 5000);
}
function hidePopup() {
document.getElementById("disclaimer").style.display = "none";
setTimeout(popup, 5000);
}
<div id="disclaimer">
<div><img src="http://dummyimage.com/100x100/100/fff"></div>
<div><img src="http://dummyimage.com/100x100/304/fff"></div>
</div>
CodePudding user response:
- In the HTML file you should create a div with an id disclaimer
<div id="disclaimer"></div>
- Then in the js file you should select the HTML element out of the popup function
const el = document.getElementById("disclaimer");
- And create an enter code hereimage element out of the popup function
const img = document.createElement('img')
- Then in the popup function you should create a random image every time the function get called with setTimeout to change the image src, set attribute src for image with random image number from images array, and append an image element to the div in HTML file and call setTimeout with hidepop
function popup() {
randomImage = Math.floor(Math.random() * images.length)
img.setAttribute('src', images[randomImage])
img.setAttribute('alt', 'random')
el.appendChild(img);
setTimeout(hidePopup, 1000);
}
- Then create a hidepop()
function hidePopup() {
setTimeout(popup, 1000);
}
- And call popup function
popup()
** Note: In setTimeout function don't call the handler like that
setTimeout(hidePopup(), 1000);
that will cause Maximum call stack size exceeded error and you app will crashed