Exercise 4: Interactive Image Gallery
HTML (index.html):
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<link rel=”stylesheet” href=”styles.css”>
<title>Image Gallery</title>
</head>
<body>
<div class=”gallery-container”>
<img src=”image1.jpg” alt=”Image 1″ id=”galleryImage”>
<div class=”button-container”>
<button onclick=”prevImage()”>Previous</button>
<button onclick=”nextImage()”>Next</button>
</div>
</div>
<script src=”script.js”></script>
</body>
</html>
CSS (styles.css):
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.gallery-container {
text-align: center;
}
#galleryImage {
max-width: 100%;
border: 1px solid #ccc;
}
.button-container {
margin-top: 10px;
}
button {
padding: 10px;
font-size: 16px;
}
JavaScript (script.js):
const images = [“image1.jpg”, “image2.jpg”, “image3.jpg”, “image4.jpg”];
let currentIndex = 0;
function updateImage() {
const galleryImage = document.getElementById(‘galleryImage’);
galleryImage.src = images[currentIndex];
}
function prevImage() {
currentIndex = (currentIndex – 1 + images.length) % images.length;
updateImage();
}
function nextImage() {
currentIndex = (currentIndex + 1) % images.length;
updateImage();
}
// Initial image update
updateImage();
Explanation:
- The HTML file contains an image element and buttons for navigating through the gallery.
- The CSS file provides styling for the gallery display.
- The JavaScript file includes an array of image filenames and functions (prevImage, nextImage, and updateImage) to handle image navigation.