Skip to content

Instantly share code, notes, and snippets.

@hassanrazadev
Created March 20, 2023 14:41
Show Gist options
  • Save hassanrazadev/495ed1ae7be0089ba0a358977c49f43f to your computer and use it in GitHub Desktop.
Save hassanrazadev/495ed1ae7be0089ba0a358977c49f43f to your computer and use it in GitHub Desktop.
Simple image slider with HTML, CSS, and JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style>
.slider {
display: flex;
max-width: 640px;
overflow: hidden;
margin-left: auto;
margin-right: auto;
border: 1px solid;
}
.slider-image {
position: relative;
left: 0;
transition: left .4s;
}
</style>
<body>
<div class="container">
<div class="slider">
<img src="https://placebear.com/640/360" alt="image 1" id="image1" class="slider-image">
<img src="https://placebeard.it/640x360" alt="image 2" id="image2" class="slider-image">
<img src="https://baconmockup.com/640/360" alt="image 3" id="image3" class="slider-image">
<img src="https://loremflickr.com/640/360" alt="image 4" id="image4" class="slider-image">
</div>
<div style="text-align: center; margin-top: 10px">
<button id="prev">&lt;</button>
<button id="next">&gt;</button>
</div>
</div>
<script type="text/javascript">
let images = document.querySelectorAll('.slider-image');
let activeImage = 0;
prev.addEventListener('click', function (e) {
e.preventDefault();
let nextActive = (activeImage - 1) % images.length;
images.forEach(function (image, index) {
image.style.left = '-' + (nextActive * 100) + '%';
});
activeImage--;
});
next.addEventListener('click', function (e) {
e.preventDefault();
let nextActive = (activeImage + 1) % images.length;
images.forEach(function (image, index) {
image.style.left = '-' + (nextActive * 100) + '%';
});
activeImage++;
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment