Image changes when the page refreshes and I am accomplishing this but I can't add individual image links. how can I do it? Please have me out.. here is the code
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
#banner-images img{
width: 172px;
height: 215px ;
border: 10px solid #fff ;
}
</style>
</head>
<body>
<div id="banner-images"> </div>
<script>
var images = ['1.jpg ', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg'];
$('<img src="images/' images[Math.floor(Math.random() * images.length)] '">').appendTo('#banner-images');
</script>
</body>
</html>
CodePudding user response:
I hope i understood your question correctly. Here is a solution.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
#banner-images img{
width: 172px;
height: 215px ;
border: 10px solid #fff ;
}
</style>
</head>
<body>
<div id="banner-images"> </div>
<script>
var images = [
{src: '1.jpg', href: '#link1'},
{src: '2.jpg', href: '#link2'},
{src: '3.jpg', href: '#link3'},
{src: '4.jpg', href: '#link4'}
];
var random_image = images[Math.floor(Math.random() * images.length)];
$('<a href="' random_image.href '"><img src="images/' random_image.src '"></a>').appendTo('#banner-images');
</script>
</body>
</html>
If you want to make it clearer, you can do it this way with JavaScript Template Literals.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
#banner-images img{
width: 172px;
height: 215px ;
border: 10px solid #fff ;
}
</style>
</head>
<body>
<div id="banner-images"></div>
<script>
var images = [
{src: '1.jpg', href: '#link1'},
{src: '2.jpg', href: '#link2'},
{src: '3.jpg', href: '#link3'},
{src: '4.jpg', href: '#link4'}
];
var random_image = images[Math.floor(Math.random() * images.length)];
$('#banner-images').html(`
<a href="${random_image.href}">
<img src="images/${random_image.src}">
</a>
`);
</script>
</body>
</html>