Simple Pure JS Slider

HTML
<section class="slider-wrapper"> <button class="slide-arrow" id="slide-arrow-prev"> <svg xmlns="http://www.w3.org/2000/svg" height="24" width="24"><path d="M10.9 23.025-.15 12 10.9.95l2.725 2.75-8.3 8.3 8.3 8.3Z"/></svg> </button> <button class="slide-arrow" id="slide-arrow-next"> <svg xmlns="http://www.w3.org/2000/svg" height="24" width="24"><path d="M8 23.025 5.25 20.3l8.3-8.3-8.3-8.3L8 .95 19.025 12Z"/></svg> </button> <ul class="slides-container" id="slides-container"> <li class="slide"></li> <li class="slide"></li> </ul> </section>
CSS
* { box-sizing: border-box; } body { max-width: 1440px; margin: auto; } .slider-wrapper { position: relative; overflow: hidden; } .slides-container { height: calc(100vh - 2rem); width: 100%; display: flex; overflow: hidden; scroll-behavior: smooth; list-style: none; margin: 0; padding: 0; } .slide-arrow { position: absolute; display: flex; top: 0; bottom: 0; margin: auto; height: 4rem; background-color: white; border: none; width: 2rem; font-size: 3rem; padding: 0; cursor: pointer; opacity: 0.5; transition: opacity 100ms; justify-content:center; align-items:center; } .slide-arrow svg{ } .slide-arrow:hover, .slide-arrow:focus { opacity: 1; } #slide-arrow-prev { left: 0; padding-left: 0.25rem; border-radius: 0 2rem 2rem 0; } #slide-arrow-next { right: 0; padding-left: 0.75rem; border-radius: 2rem 0 0 2rem; } #slide-arrow-next svg{ display:inline-block; position:relative; right:4px; } .slide { width: 100%; height: 100%; flex: 1 0 100%; } .slide:nth-child(1) { background-color: #49b293; } .slide:nth-child(2) { background-color: #b03532; }
JAVASCRIPT
const slidesContainer = document.getElementById("slides-container"); const slide = document.querySelector(".slide"); const prevButton = document.getElementById("slide-arrow-prev"); const nextButton = document.getElementById("slide-arrow-next"); nextButton.addEventListener("click", () => { const slideWidth = slide.clientWidth; slidesContainer.scrollLeft += slideWidth; }); prevButton.addEventListener("click", () => { const slideWidth = slide.clientWidth; slidesContainer.scrollLeft -= slideWidth; });
Expand for more options Login