JavaScript Program to Display Random Header Images

I am currently working on implementing a dynamic feature for my client. They need a JavaScript function that randomly displays a background image in the header of their webpage each time the page loads. Here’s how I’m handling it:

JavaScript Code:

codefunction displayRandomHeaderImage() {
// Array of image URLs
const images = [
"url_to_image_1.jpg",
"url_to_image_2.jpg",
"url_to_image_3.jpg",
// Add more image URLs as needed
];

// Generate a random index
const randomIndex = Math.floor(Math.random() * images.length);

// Set the header image
document.getElementById("header").style.backgroundImage = `url(${images[randomIndex]})`;
}

// Call the function on page load
window.onload = displayRandomHeaderImage;

Explanation:

  1. Image Array: I’ve created an array named images to store the URLs of all the background images the client wants to use for the header.
  2. Random Index: To select an image randomly, I use JavaScript’s Math.random() to generate a random decimal number. Then, I multiply it by the length of the array and use Math.floor() to convert it into a valid index.
  3. Set Header Image: Using document.getElementById("header"), I target the <header> element. I then dynamically set its backgroundImage CSS property to the randomly chosen image.
  4. Call on Page Load: To ensure the header image changes every time the page loads, I attach the displayRandomHeaderImage() function to the window.onload event.

HTML Structure:

code<header id="header">
</header>

The <header> element is given an id of header, which is used in the JavaScript to identify and manipulate the element.

Usage Note:

I will replace the placeholder image URLs ("url_to_image_1.jpg", "url_to_image_2.jpg", etc.) with the actual image URLs provided by the client.

Let me know if you need any adjustments, such as adding transitions for a smoother effect or changing the logic to refresh images at specific intervals 😊

Related blog posts