-
-
Save ef4/90d1e1c37e6176c8a7e3 to your computer and use it in GitHub Desktop.
An ember component for scrolling the page.
This file contains 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
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); | |
} | |
}); | |
} | |
}); |
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
If you use this component within a template, it will scroll with animation to that point when the component is rendered:
If you use it inside an
{{#if}}
, you can trigger the scrolling whenever the condition goes from false to true: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.