Repository navigation
[Help]: I was wondering it was possible to start the carousel centered #1038
SummaryI was wondering if it was possible to start the carousel items centred or can it only start with the first item at the start, center or end? I have the slider like this and the distance of the controls are very wide when there are less items in the carousel. I'm trying to get something like this or the controls on the outside contract in depending on the number of the items in the slider. If applicable, which variants of Embla Carousel are relevant to this question?
Additional informationI'm using the CDN method with the following setup for the code.
<script src="https://unpkg.com/embla-carousel/embla-carousel.umd.js"></script>
<script src="https://unpkg.com/embla-carousel-autoplay/embla-carousel-autoplay.umd.js"></script>
<script>
// Grab wrapper nodes
const emblaNode = document.querySelector('.embla');
// Grab button nodes
const prevButtonNode = emblaNode.querySelector('.embla__button--prev');
const nextButtonNode = emblaNode.querySelector('.embla__button--next');
const options = {
slidesToScroll: 'auto',
};
const plugins = [EmblaCarouselAutoplay()];
// Initialize the carousel
const emblaApi = EmblaCarousel(emblaNode, options, plugins);
// Add click listeners
prevButtonNode.addEventListener('click', emblaApi.scrollPrev, true);
nextButtonNode.addEventListener('click', emblaApi.scrollNext, true);
</script>CodeSandbox exampleNo response |
Answered by
leebaroneau
Nov 25, 2024
Replies: 3 comments 1 reply
|
Hi @leebaroneau, Thanks for your question.
const options = {
slidesToScroll: 'auto',
align: (viewSize, snapSize, index) => {
// return your own alignment which should be a number;
}
};
|
1 reply
|
Hi @leebaroneau, |
0 replies
|
My solution was to calculate an offset based on the number of slides in the slider. const options = {
containScroll: false,
loop: true,
align: (viewSize, snapSize, index) => {
console.log(viewSize, snapSize, index);
let slideElement = document.querySelector('.embla__slide');
let slideCount = document.querySelectorAll('.embla__slide').length;
let slideWidth = slideElement.offsetWidth;
let slideNumber = viewSize / slideWidth;
if (slideCount < slideNumber) {
// Get all elements with the class 'embla__button'
const buttons = document.querySelectorAll('.embla__button');
// Iterate over each button and set its display style to 'none'
buttons.forEach(button => {
button.style.display = 'none';
});
console.log(slideCount, slideNumber, slideWidth);
let offsetSlider = ((slideNumber - slideCount) * slideWidth) / 2;
console.log(offsetSlider);
return offsetSlider;
} else {
return 0;
}
},
}; |
0 replies
Answer selected by
davidjerleke
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment


My solution was to calculate an offset based on the number of slides in the slider.