Skip to content

Instantly share code, notes, and snippets.

@dtuite
Created February 11, 2014 12:53
Show Gist options
  • Save dtuite/8934298 to your computer and use it in GitHub Desktop.
Save dtuite/8934298 to your computer and use it in GitHub Desktop.
Code sample for displaying sharing bar when certain percentage scrolled
<div class="share-bar">
<%= @post.tweet_button -%>
<%= @post.share_button -%>
<%# No point showing this on mobiles since they can't easily copy/paste
the URL into an RSS app. %>
<%= @post.rss_button unless mobile_device? -%>
</div>
# Show an element when we are scrolled down past a certain point on the page
# but hide it otherwise.
jQuery.fn.showWhenScrolled = (options = {}) ->
$window = $(window)
$element = @
elementVisible = false
if options.percentToShowBar
# Calculate the point as a percentage of the height of the page.
pointToShowBar = options.percentToShowBar * 0.01 * $(document).height()
else
pointToShowBar = options.pointToShowBar || 600
checkPosition = ->
if $window.scrollTop() > pointToShowBar and !elementVisible
$element.slideDown 'fast', -> elementVisible = true
else if $window.scrollTop() < pointToShowBar and elementVisible
$element.slideUp 'fast', -> elementVisible = false
# Using setInterval because listenting to the 'scroll' event causes a severe
# preformance hit: http://ejohn.org/blog/learning-from-twitter/
setInterval(checkPosition, 500)
jQuery ->
$('.share-bar').showWhenScrolled(percentToShowBar: 30)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment