Skip to content

Instantly share code, notes, and snippets.

@jlsync
Created March 6, 2015 15:47
Show Gist options
  • Save jlsync/2cdbafa12aea1a0584ee to your computer and use it in GitHub Desktop.
Save jlsync/2cdbafa12aea1a0584ee to your computer and use it in GitHub Desktop.
jscrollTo - scroll page to bring element into view
$ = jQuery
$window = $(window)
methods =
init: (options = {}) ->
return this.each () ->
$this = $(this)
offset = $this.offset()
x = undefined
y = undefined
st = $window.scrollTop()
sl = $window.scrollLeft()
if ( offset.left ) < sl
x = if offset.left - 20 < 0 then 0 else offset.left - 20
else if offset.left + $this.outerWidth() > ( sl + $window.width() + 1 )
x = offset.left - 20
if ( offset.top - 150 ) < st
y = offset.top - 150
else if (offset.top + $this.outerHeight()) + 50 > (st + $window.height())
y = 50 + offset.top + $this.outerHeight() - $window.height()
if x? or y?
x ?= 0
y ?= 0
scrollTo x, y
$.fn.jscrollTo = (method) ->
if methods[method]?
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ))
else if typeof method == 'object' or ! method
return methods.init.apply( this, arguments )
else
$.error( 'Method ' + method + ' does not exist on jQuery.jscrollTo' )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment