teelim14
New Coder
JavaScript:
document.addEventListener('DOMContentLoaded', init);
const baseURL = 'images/';
const nxt = document.querySelector('.nxt');
const bck = document.querySelector('.prev');
const slide = document.querySelector('.pic');
const cars = ['images/280z.jpg', 'images/300zx.jpg', 'images/cosworth.jpg', 'images/m3.jpg'];
let index = 1; //specifies that array starts at 1 because page loads with 0
function init() {
// Set the initial image source to the first image in the 'cars' array
slide.src = baseURL + cars[index];
}
nxt.onclick = function(e) {
e.preventDefault(); // ignores event so page wont reload
// Increment the index to the next image in the array
index++;
// If the index is greater than or equal to the length of the array, reset it to 0
if (index >= cars.length) {
index = 0;
}
// Set the image source to the next image in the array
slide.src = baseURL + cars[index];
};
HTML:
<h1>Slides!</h1>
<p>I reccommend you to export this pen and use your own images.</p>
<div class="slides">
<figure>
<img class="pic" src="images/280z.jpg">
</figure>
<a class="prev" href="">previous</a>
<a class="nxt" href="">next</a>
</div>
CSS:
h1 {
text-align: center;
}
img {
display: block;
}
.slides {
width:400px;
margin:auto;
}
.slides figure {
margin:0;
}
.slides .nxt {
float:right;
}
Last edited by a moderator: