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();

No comments:

Post a Comment

Random Image