Last active
October 30, 2015 18:57
-
-
Save shannon/d698a7bbd0ecbe261da6 to your computer and use it in GitHub Desktop.
Simple angular typeout directive
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('typeOut', []) | |
| .directive('typeOut', ["$timeout", function($timeout){ | |
| return { | |
| restrict: 'A', | |
| scope: { | |
| text: '=typeOut', | |
| speed: '=typeOutSpeed', | |
| onComplete: '&', | |
| }, | |
| link: function($scope, elem, attrs){ | |
| var start = Date.now(); | |
| $scope.speed = $scope.speed || 10; | |
| $timeout(function render(){ | |
| var now = Date.now(); | |
| var delta = now - start; | |
| var chars = Math.floor(delta / 1000 * $scope.speed); | |
| var words, pos = 0, text = '', i = 0; | |
| if(chars >= $scope.text.length){ | |
| elem[0].innerHTML = $scope.text; | |
| $scope.onComplete(); | |
| }else { | |
| words = $scope.text.split(' '); | |
| for(i = 0; i < words.length; i++){ | |
| pos += words[i].length; | |
| if(pos > chars){//last word is clipped | |
| words[i] = '<span style="white-space: nowrap;">' | |
| + words[i].substr(0, words[i].length - (pos - chars)) | |
| + '<span style="color:transparent">' + words[i].substr(-(pos - chars)) + '</span>' | |
| + '</span>'; | |
| words.length = i + 1; | |
| break; | |
| } else if(pos === chars){ //last word full | |
| words.length = i + 1; | |
| break; | |
| } | |
| pos += 1; //add for space | |
| } | |
| elem[0].innerHTML = words.join(' '); | |
| $timeout(render, 50); | |
| } | |
| }, 50); | |
| } | |
| } | |
| }]) |
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
| <html ng-app="app"> | |
| <head> | |
| <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script> | |
| <script src="angular-typeout.js"></script> | |
| <script> | |
| angular.module('app', ['typeOut']).controller('AppCtrl', function($scope){ | |
| $scope.text = 'this is some text'; | |
| $scope.complete = function(){ | |
| alert('done'); | |
| } | |
| }); | |
| </script> | |
| </head> | |
| <body ng-controller="AppCtrl"> | |
| <p type-out="text" type-out-speed="10" on-complete="complete()"></p> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment