Skip to content

Instantly share code, notes, and snippets.

@jerel
Created June 27, 2014 16:46
Show Gist options
  • Save jerel/a536f931f78566063401 to your computer and use it in GitHub Desktop.
Save jerel/a536f931f78566063401 to your computer and use it in GitHub Desktop.
A loading animation for EmberJS that is similar to the Youtube animation. A bar shoots across the top of the viewport from left to right.
// CSS
div.loading-slider {
overflow: hidden;
height: 2px;
span {
float: left;
height: 2px;
background-color: red;
}
}
// Application Route
export default Ember.Route.extend({
actions: {
loading: function(transition) {
var controller = this.controllerFor('application');
controller.set('loading', true);
this.router.one('didTransition', function() {
controller.set('loading', false);
});
}
}
});
// Application Template
{{loading-slider isLoading=loading duration=450}} // duration isn't critical... it's an estimate of how many ms the process will take
// loading-slider.js Component
export default Ember.Component.extend({
tagName: 'div',
classNames: ['loading-slider'],
manage: function() {
if (this.get('isLoading')) {
this.animate.call(this);
} else {
this.set('isLoaded', true);
}
}.observes('isLoading'),
animate: function() {
this.set('isLoaded', false);
var self = this,
elapsedTime = 0,
inner = this.$().find('span'),
duration = this.getWithDefault('duration', 300),
innerWidth = 0,
outerWidth = this.$().width(),
stepWidth = Math.round(outerWidth / 100);
var interval = setInterval(function() {
elapsedTime = elapsedTime + 10;
inner.width(innerWidth = innerWidth + stepWidth);
// slow the animation if we used more than 75% the estimated duration
// or 66% of the animation width
if (elapsedTime > (duration * 0.75) || innerWidth > (outerWidth * 0.66)) {
// don't stop the animation completely
if (stepWidth > 1) {
stepWidth = stepWidth * 0.97;
}
}
if (innerWidth > outerWidth) {
Ember.run.later(function() {
inner.width(0);
clearInterval(interval);
}, 50);
}
// the activity has finished
if (self.get('isLoaded')) {
// start with a sizable pixel step
if (stepWidth < 10) {
stepWidth = 10;
}
// accelerate to completion
stepWidth = stepWidth + stepWidth;
}
}, 10);
},
didInsertElement: function() {
this.$().html('<span>');
}
});
@GheorgheoiuNicolae
Copy link

can this be made to wait for images to load?

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