Skip to content

Instantly share code, notes, and snippets.

@mrmolaei
Created February 5, 2023 02:52
Show Gist options
  • Save mrmolaei/8ef28bfb73ed7c72e40aa2971495c952 to your computer and use it in GitHub Desktop.
Save mrmolaei/8ef28bfb73ed7c72e40aa2971495c952 to your computer and use it in GitHub Desktop.
Mouse wheel scroll on Flickity slider
// Include https://github.com/jquery/jquery-mousewheel
if (document.querySelector('.js-carousel')) {
const flickityElement = jQuery('.js-carousel').flickity({
prevNextButtons: false,
pageDots: false,
contain: true,
freeScroll: true,
cellAlign: 'left',
imagesLoaded: true
});
jQuery('.js-carousel').on('mousewheel', function (event) {
const firstCell = jQuery('.js-carousel .flickity-slider .c-carousel__slide:first-child').offset()
const lastCell = Math.round(jQuery('.js-carousel .flickity-slider .c-carousel__slide:last-child').offset().left)
const sliderWidth = Math.round(jQuery('.js-carousel .flickity-slider').width() - jQuery('.js-carousel .flickity-slider .c-carousel__slide:last-child').width())
if (jQuery('.js-carousel .flickity-slider .c-carousel__slide:last-child').visible()){
jQuery('.js-carousel .flickity-slider .c-carousel__slide:last-child').addClass('is-selected')
} else {
jQuery('.js-carousel .flickity-slider .c-carousel__slide:last-child').removeClass('is-selected')
}
if (event.deltaY === -1) {
if (sliderWidth <= lastCell) {
event.preventDefault();
event.stopPropagation();
const flickity = flickityElement.data("flickity"); // [1]
flickity.velocity = -12; // [2]
flickity.isFreeScrolling = true; // [3]
flickity.startAnimation(); // [4]
flickityElement.trigger('settle.flickity')
flickityElement.flickity( 'select', jQuery('.js-carousel .flickity-slider .c-carousel__slide').length )
}
} else {
if (Math.round(firstCell.left) < 50) {
event.preventDefault();
event.stopPropagation();
const flickity = flickityElement.data("flickity"); // [1]
flickity.velocity = 12; // [2]
flickity.isFreeScrolling = true; // [3]
flickity.startAnimation(); // [4]
flickityElement.flickity( 'select', 0 )
}
}
});
setInterval(function () {
const currTrans = jQuery('.js-carousel .flickity-slider').css('transform').split(/[()]/)[1];
const sliderXPos = currTrans.split(',')[4];
if (sliderXPos > 0) {
flickityElement.flickity( 'select', 1 )
flickityElement.flickity( 'select', 0 )
}
}, 2000)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment