Last active
December 30, 2015 04:09
-
-
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…
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
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()) | |
]) |
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
Some css to make the media query aspect more concrete: