Skip to content

Instantly share code, notes, and snippets.

@samleb
Created September 6, 2013 10:15
Show Gist options
  • Save samleb/6462030 to your computer and use it in GitHub Desktop.
Save samleb/6462030 to your computer and use it in GitHub Desktop.
function Scroller(track, handle) {
var handleWidth = handle.width(),
maxX = track.width() - handleWidth,
dragX
handle.on('mousedown', setupDrag)
track.on('mousedown', '.arrow', arrowClicked)
.on('mousedown', trackClicked)
function arrowClicked(e) {
}
function setupDrag(e) {
doc.one('mousemove', startDrag)
.one('mouseup', stopDrag)
return false
}
function startDrag(e) {
dragX = parseFloat(handle.css('left')) - e.pageX
doc.on('mousemove', drag)
}
function drag(e) {
updateHandlePosition(dragX + e.pageX)
}
function stopDrag() {
doc.off('mousemove')
}
function trackClicked(e) {
var x = e.pageX - track.offset().left - handleWidth / 2
updateHandlePosition(x)
}
function updateHandlePosition(x) {
if (x < 0) x = 0
if (x > maxX) x = maxX
handle[0].style.left = x + 'px'
handle.trigger('scroll', x / maxX * 100)
}
function moveHandle(x, animate) {
handle[animate ? 'animate' : 'css']({ left: x / 100 * maxX }, 1000, 'swing')
}
return {
moveHandle: moveHandle
}
}
$.fn.productSelector = function() {
var el = this,
productsContainer = el.find('.products'),
products = productsContainer.find('.product'),
containerWidth = products.length * products.width(),
scrollTrack = el.find('.categories_wrapper'),
scrollHandle = scrollTrack.find('.scroller'),
offsetWidth = containerWidth - el.find('.wrapper').width(),
scroller = Scroller(scrollTrack, scrollHandle),
currentProduct = products.filter('.current')[0]
productsContainer.width(containerWidth)
el.find('.categories a').on('mousedown', categoryClicked)
scrollHandle.on('scroll', handleScrolled)
if (currentProduct) centerOnProduct(currentProduct)
function centerOnProduct(product) {
var index = products.index(currentProduct) - 2
if (index < 0) index = 0
if (index > products.length - 5) index = products.length - 5
moveToIndex(index, false)
}
function handleScrolled(e, scrollX) {
productsContainer[0].style.left = -(offsetWidth / 100 * scrollX) + 'px'
return false
}
function categoryClicked(e) {
var name = $(e.target).attr('href').replace(/^#/, ''),
categoryProducts = products.filter('[data-category="' + name + '"]'),
index = Math.min(products.index(categoryProducts[0]), products.length - 5)
moveToIndex(index, true)
return false
}
function moveToIndex(index, animate) {
var scrollX = index / (products.length - 5) * 100
productsContainer[animate ? 'animate' : 'css']({ left: -(offsetWidth / 100 * scrollX) }, 1000, 'swing')
scroller.moveHandle(scrollX, animate)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment