Reputation: 1
I am not a true programmer and need some help. I need a script that inserts a div tag and within that div tag have a random image load (from a list of 10) when the page laods from an external js file.
I searched and searched and tried different ways but really need help.
Thanks
Upvotes: 0
Views: 280
Reputation: 2313
Just wanted to throw in vanilla JS answer as well.
<style>
#show-picture {
display: block;
margin: 20px;
height: 400px;
width: 400px;
box-shadow: 0 0 12px rgba(0,0,0,0.25);
background-size: cover;
background-position: center;
}
</style>
<div id="show-picture"></div>
<script>
const images = [
'https://picsum.photos/400/400?image=600',
'https://picsum.photos/400/400?image=601',
'https://picsum.photos/400/400?image=602',
'https://picsum.photos/400/400?image=603',
'https://picsum.photos/400/400?image=604',
'https://picsum.photos/400/400?image=605',
'https://picsum.photos/400/400?image=606',
'https://picsum.photos/400/400?image=607',
'https://picsum.photos/400/400?image=608',
'https://picsum.photos/400/400?image=609',
]
// get random image
const random_number = Math.floor(Math.random() * images.length);
const image = images[random_number];
// get div and set background-image CSS to be our random image
const show_picture = document.getElementById('show-picture');
show_picture.style.backgroundImage = `url(${image})`;
</script>
Upvotes: 0
Reputation: 1777
The solution below uses jQuery, but it can be achieved without it in a simple way
$(document).ready(function() {
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var imageUrls = [
"https://www.gstatic.com/webp/gallery3/1.sm.png",
"https://www.gstatic.com/webp/gallery3/2.sm.png",
"https://www.gstatic.com/webp/gallery3/3.sm.png"
];
var randomImage = imageUrls[randomInt(0, imageUrls.length - 1)];
$(".container").append("<img alt='" + randomImage + "' src='" + randomImage + "'</>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
</div>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<script type="text/javascript">
/**
* Loads a random number
*/
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// List of urls
var imageUrls = [
"https://www.gstatic.com/webp/gallery3/1.sm.png",
"https://www.gstatic.com/webp/gallery3/2.sm.png",
"https://www.gstatic.com/webp/gallery3/3.sm.png"
];
function loadRandomImage() {
var randomImage = imageUrls[randomInt(0, imageUrls.length - 1)];
$(".container").append(
"<img alt='" + randomImage + "' src='" + randomImage + "'</>");
}
// This function executes when the DOM is ready,
// e.g., when the entire page is loaded
$(document).ready(function() {
loadRandomImage()
});
</script>
</head>
<body>
<div class="container">
</div>
</body>
</html>
Upvotes: 1