Skip to content

Instantly share code, notes, and snippets.

@ef4
Created May 12, 2014 15:37
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 ef4/90d1e1c37e6176c8a7e3 to your computer and use it in GitHub Desktop.
Save ef4/90d1e1c37e6176c8a7e3 to your computer and use it in GitHub Desktop.
An ember component for scrolling the page.
export default Ember.Component.extend({
altTarget: null,
didInsertElement: function() {
return Em.run.schedule('afterRender', this, function() {
var current, goal, maximum, w, _ref;
w = $(window);
current = w.scrollTop();
maximum = $(document).height() - w.height();
goal = (_ref = this.get('altTarget')) != null ? _ref : this.$().offset().top;
if (goal > maximum) {
goal = maximum;
}
return this.scroll({
from: current,
to: goal,
"in": 500
});
});
},
scroll: function(kwargs) {
var endTime, startTime;
startTime = (new Date).getTime();
endTime = startTime + kwargs["in"];
return this.animation(startTime, endTime, kwargs.from, kwargs.to);
},
animation: function(startTime, endTime, from, to) {
var _this = this;
return requestAnimationFrame(function() {
var fraction, frction, interp;
fraction = ((new Date).getTime() - startTime) / (endTime - startTime);
if (fraction < 0) {
fraction = 0;
}
if (fraction > 1) {
frction = 1;
}
interp = Math.sin(Math.PI * fraction / 2) * (to - from) + from;
$(window).scrollTop(interp);
if (fraction < 1) {
return _this.animation(startTime, endTime, from, to);
}
});
}
});
@ef4
Copy link
Author

ef4 commented May 12, 2014

If you use this component within a template, it will scroll with animation to that point when the component is rendered:

{{scroll-here}}

If you use it inside an {{#if}}, you can trigger the scrolling whenever the condition goes from false to true:

{{#if showing-faq}}{{scroll-here}}{{/if}}

This is one way to implement routes inside a single scrollable page -- make all the routes render the same template, make the controller expose variables you can test to tell which route you're inside, and use scroll-here to scroll to the appropriate place.

@ef4
Copy link
Author

ef4 commented May 12, 2014

The component uses requestAnimationFrame, if you need to support browsers without it you will need to add a polyfill.

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