Skip to content

Instantly share code, notes, and snippets.

@guapodero
Last active December 30, 2015 04:09
Show Gist options
  • Save guapodero/7774535 to your computer and use it in GitHub Desktop.
Save guapodero/7774535 to your computer and use it in GitHub Desktop.
Derived from http://isotope11.com/blog/make-a-snappable-cart-directive-with-angularjs Usage <div scrollfollow="45" id="scrollfollow1"> I stick to the viewport on scroll, 45 pixels from the top. I'll stay aligned to a grid like that of Bootstrap 3, leaving the normal page flow without creating a wake. You can also disable me with media queries an…
angular.module("ui-utils-too", []).
directive("scrollfollow", ["$window", ($window) ->
restrict: "A"
link: (scope, el, attrs) ->
window = angular.element($window)
parent = angular.element(el.parent())
currentOffsetTop = el[0].getBoundingClientRect().top
headerOffsetTop = scope.$eval(attrs.scrollfollow) || 5
# assumes width/padding in px
getParentWidth = ->
returnDigit = (val) -> val.match(/\d+/)[0]
returnDigit(parent.css("width")) -
returnDigit(parent.css("padding-left")) -
returnDigit(parent.css("padding-right"))
handleSnapping = ->
dynamicContent = $("#" + el.attr("id")).css("content")
if (dynamicContent != "tablet" && window[0].scrollY > currentOffsetTop)
el.addClass("scrollfollowing")
el.css(
position: "fixed"
top: headerOffsetTop + "px"
width: getParentWidth()
)
el.next().css(height: el[0].offsetHeight, display: "block")
else
el.removeClass("scrollfollowing")
el.css(position: "static", width: getParentWidth())
el.next().css("display": "none")
placeholder = document.createElement("div")
placeholder.className = "scrollfollow_placeholder"
placeholder.style.display = "none"
el.after(placeholder)
handleSnapping()
window.bind "scroll", -> handleSnapping()
window.bind "resize", -> el.css(width: getParentWidth())
])
@guapodero
Copy link
Author

Some css to make the media query aspect more concrete:

// tablet and below
@media (max-width: 991px) {
  #scrollfollow1 {
    content: 'tablet';
  }
}
// desktop and above
@media (min-width: 992px) {
  #scrollfollow1 {
    content: 'desktop';
  }
}

@joelcrocker
Copy link

To prevent the element from jumping when you scroll, I changed the handleSnapping if condition to the following:

if (dynamicContent != "tablet" && window[0].scrollY > currentOffsetTop - headerOffsetTop)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment