Sunday, January 26, 2025
Random Image
/*HTML
*/
function loadRandomPicture() {
// Array of 10 possible picture file names
const imageFiles = [
"image1.jpg",
"image2.jpg",
"image3.jpg",
"image4.jpg",
"image5.jpg",
"image6.jpg",
"image7.jpg",
"image8.jpg",
"image9.jpg",
"image10.jpg"
];
// Generate a random index within the range of the array
const randomIndex = Math.floor(Math.random() * imageFiles.length);
// Get the randomly selected file name
const randomImage = imageFiles[randomIndex];
// Create an image element
const img = new Image();
// Set the source of the image element
img.src = randomImage;
// Add an event listener to handle image loading
img.onload = () => {
// Once the image is loaded, display it (e.g., in an HTML element)
document.getElementById("image-container").appendChild(img);
};
// Add an event listener to handle image loading errors
img.onerror = () => {
console.error(`Error loading image: ${randomImage}`);
// Handle the error (e.g., display an error message)
};
}
// Call the function to load a random picture
loadRandomPicture();
Subscribe to:
Post Comments (Atom)
-
**See 6/22 post for adjustments.** Code can be tested at https://www.programiz.com/python-programming/online-compiler/ (Remove the 3 lines ...
-
I forgot to put the spellchecker conditional back in, and when I did I realized "elif" had to be used. Otherwise, it would skip in...
No comments:
Post a Comment