257 votes
0 answers
javascript - Loop Back to First Image Carousel Slider
I'm having trouble with my product image slider, when it gets to the end the Shopify default no image gets returned. I'd like it to loop back to the first image instead, so that the user can go back to first product featured image. Here's the essential code, any help on this greatly appreciated.
HTML
<div class="product-gallery container">
<button id="left-btn"><i class="arrow"></i></button>
<img class="product-gallery--viewport--figure" id="carousel" src="" />
<button id="right-btn"><i class="arrow"></i></button>
</div>
CSS
.container {
width: 50%;
height: auto;
display: flex;
align-items: flex-start;
flex-wrap: wrap;
margin-bottom: 315px;
}
.container::after {
margin-bottom: 315px;
}
.container img {
z-index: -2;
width: 100%;
}
button {
border: none;
outline: none;
background: rgba(0, 0, 0, 0.5);
cursor: pointer;
padding: 1em;
display: flex;
}
button .arrow {
border: solid #fff;
border-width: 0 2px 2px 0;
display: inline-block;
padding: 10px;
transition: transform 0.3s ease-out;
outline: none;
}
#right-btn .arrow {
transform: rotate(-45deg);
margin-top: 5px;
margin-left: 5px;
width: 26px;
height: 26px;
}
#left-btn .arrow {
transform: rotate(135deg);
margin-top: 5px;
margin-left: 5px;
width: 26px;
height: 26px;
}
#left-btn {
z-index: 0;
left: 0;
top: 20.5%;
position: absolute;
background: transparent;
}
#right-btn {
z-index: 0;
left: 45.5%;
top: 20.5%;
position: absolute;
background: transparent;
}
JavaScript
const img = document.getElementById('carousel');
const rightBtn = document.getElementById('right-btn');
const leftBtn = document.getElementById('left-btn');
// Pull images from Shopify CDN
let pictures = [{{ product.media[0] | img_url: '500x' | json }},{{ product.media[1] | img_url: '500x' | json }},{{ product.media[2].src | img_url: '500x' | json }},{{ product.media[3].src | img_url: '500x' | json }},{{ product.media[4].src | img_url: '500x' | json }},{{ product.media[5].src | img_url: '500x' | json }},{{ product.media[6].src | img_url: '500x' | json }}];
img.src = pictures[0];
let position = 0;
const moveRight = () => {
if (position >= pictures.length - 1) {
position = 0;
img.src = pictures[position];
return;
}
img.src = pictures[position + 1];
position++;
}
const moveLeft = () => {
if (position < 1) {
position = pictures.length - 1;
img.src = pictures[position];
return;
}
img.src = pictures[position - 1];
position--;
}
rightBtn.addEventListener("click", moveRight);
leftBtn.addEventListener("click", moveLeft);
Undefined asked
Source
Didn't find the answer?
Our community is visited by hundreds of Shopify development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.