Skip to content

Instantly share code, notes, and snippets.

@m3g4p0p
Created February 26, 2018 19:07
Show Gist options
  • Save m3g4p0p/88460a7b6ef5f003534e72596bd845e8 to your computer and use it in GitHub Desktop.
Save m3g4p0p/88460a7b6ef5f003534e72596bd845e8 to your computer and use it in GitHub Desktop.
jQuery plugin for scroll slides
$.fn.scrollSlide = function (fadeDuration) {
var $slides = this
var $window = $(window)
var $document = $(document)
var isAnimating = false
var currentSlide = 0
var toggleIsAnimating = function (forceValue) {
isAnimating = forceValue === undefined ? !isAnimating : forceValue
}
var showNext = function () {
var nextSlide = (currentSlide + 1) % $slides.length
toggleIsAnimating(true)
$slides.eq(currentSlide).fadeOut(fadeDuration, function () {
$slides.eq(nextSlide).fadeIn(fadeDuration, toggleIsAnimating)
currentSlide = nextSlide
})
}
var showPrev = function () {
var prevSlide = ($slides.length + currentSlide - 1) % $slides.length
toggleIsAnimating(true)
$slides.eq(currentSlide).fadeOut(fadeDuration, function () {
$slides.eq(prevSlide).fadeIn(fadeDuration, toggleIsAnimating)
currentSlide = prevSlide
})
}
var handleWheel = function (event) {
if (isAnimating) {
return
}
var scrollTop = $window.scrollTop()
var windowHeight = $window.height()
var documentHeight = $document.height()
if (
event.deltaY < 0 &&
scrollTop === 0
) {
showPrev()
} else if (
event.deltaY > 0 &&
scrollTop + windowHeight === documentHeight
) {
showNext()
}
}
var handleKeyup = function (event) {
if (isAnimating) {
return
}
if (event.code === 'ArrowUp') {
showPrev()
} else if (event.code === 'ArrowDown') {
showNext()
}
}
window.addEventListener('wheel', handleWheel)
window.addEventListener('keyup', handleKeyup)
}
// Usage:
$('.scroll-slide').scrollSlide(100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment