Random Image (JS)
Have you ever wondered "How do I display random header images"? Maybe you have more than one and don't know how to show them to everyone? That's what Anon asked in our wishlist (Hi Anon!) and I hope this tutorial will help you!
1️⃣ Have your images ready:
Create a folder (in my example I use images/) and upload your headers into them!
2️⃣ JavaScript:
Copy and paste this right before your </body>-Tag. Don't forget to edit the image names and how many you have!
3️⃣ HTML:
Insert this somewhere in your Design where your Header-Image would normally appear.
4️⃣ Full Example:
1️⃣ Have your images ready:
Create a folder (in my example I use images/) and upload your headers into them!
2️⃣ JavaScript:
Copy and paste this right before your </body>-Tag. Don't forget to edit the image names and how many you have!
<script>
const headers = [
"images/header.png",
"images/header2.png",
"images/header3.png",
"images/header4.png"
];
const randomHeader = headers[Math.floor(Math.random() * headers.length)];
document.getElementById("header-img").style.backgroundImage = `url('${randomHeader}')`;
</script>
3️⃣ HTML:
Insert this somewhere in your Design where your Header-Image would normally appear.
<div id="header-img" style="width: 100%; height: 300px; background-size: cover; background-position: center;"></div>
4️⃣ Full Example:
<!doctype html>
<html>
<head>
<title>Random Header</title>
<meta charset="utf-8">
<link rel="icon" href="https://designfreaks.net/placeholder/100x100?bgcolor=83160D&txtcolor=F8F9FB&text=o&fontsize=50" type="image/png">
<style>
* {
border:0;
outline:0;
margin:0;
padding:0;
box-sizing:border-box;
transition:.15s;
}
body {
color:black;
font-family:arial;
font-size:14px;
background:#333;
}
main {
margin:50px auto;
width:900px;
padding:20px;
background:#fffaf7;
}
.content { }
</style>
</head>
<body>
<main>
<div id="header-img" style="width: 100%; height: 300px; background-size: cover; background-position: center;"></div>
<div class="content">
</div>
</main>
<script>
const headers = [
"header.png",
"header2.png",
"header3.png",
"header4.png"
];
const randomHeader = headers[Math.floor(Math.random() * headers.length)];
document.getElementById("header-img").style.backgroundImage = `url('${randomHeader}')`;
</script>
</body>
</html>