Skip to content

Instantly share code, notes, and snippets.

@killercup
Forked from mataspetrikas/gist:2300296
Created May 24, 2012 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save killercup/2783854 to your computer and use it in GitHub Desktop.
Save killercup/2783854 to your computer and use it in GitHub Desktop.
Check if element is visible in viewport and scroll if necessary
$.extend $.expr[":"],
inView: (a) ->
# cf. http://remysharp.com/2009/01/26/element-in-view-event-plugin/#comment-127058
st = (document.documentElement.scrollTop or document.body.scrollTop)
ot = $(a).offset().top
wh = (if (window.innerHeight and window.innerHeight < $(window).height()) then window.innerHeight else $(window).height())
ot > st and ($(a).height() + ot) < (st + wh)
$.fn.scroll_if_necessary = ->
if this.length && not @is(":inView")
$("body").animate({scrollTop: $(this).offset().top}, 200)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment