Last active
August 29, 2015 13:57
-
-
Save benbonnet/9664268 to your computer and use it in GitHub Desktop.
Page repositionner
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
######################## | |
###### PLUGINS ######### | |
######################## | |
# scroll stops | |
$.fn.scrollStopped = (callback) -> | |
$(this).scroll -> | |
self = this | |
$this = $(self) | |
clearTimeout $this.data("scrollTimeout") if $this.data("scrollTimeout") | |
$this.data "scrollTimeout", setTimeout(callback, 250, self) | |
return | |
return | |
# scrollTo | |
$.fn.scrollTo = (target, options, callback) -> | |
if typeof options is "function" and arguments_.length is 2 | |
callback = options | |
options = target | |
settings = $.extend( | |
scrollTarget: target | |
offsetTop: 50 | |
duration: 500 | |
easing: "swing" | |
, options) | |
@each -> | |
scrollPane = $(this) | |
scrollTarget = (if (typeof settings.scrollTarget is "number") then settings.scrollTarget else $(settings.scrollTarget)) | |
scrollY = (if (typeof scrollTarget is "number") then scrollTarget else scrollTarget.offset().top + scrollPane.scrollTop() - parseInt(settings.offsetTop)) | |
scrollPane.animate | |
scrollTop: scrollY | |
, parseInt(settings.duration), settings.easing, -> | |
callback.call this if typeof callback is "function" | |
return | |
return | |
############################### | |
###### IMPLEMENTATION ######### | |
############################### | |
$scroll_enveloppe = {{whatever jq selector u want}} # most commonly, the body | |
$pointers_element = {{whatever jq selector u want}} # the elements u want to reposition to | |
pointer_value = ($pointers_element.eq(0).height() / 2) * -1 # can have different values - depends on the tolerance you want to apply | |
$scroll_enveloppe.scrollStopped -> | |
detectClosestElement() | |
detectClosestElement: -> | |
scrollPos = $scroll_enveloppe.scrollTop() | |
selectedElement = null | |
$pointers_element.each -> | |
if $(this).position().top >= pointer_value | |
reposition $pointers_element.index $(this) | |
return false | |
reposition: (indexer) -> | |
scrollTarget = indexer * $pointers_element.height() | |
$scroll_enveloppe.scrollTo scrollTarget, | |
duration: 250 | |
offsetTop: 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment