Skip to content

Commit

Permalink
Add a bunch of callback options.
Browse files Browse the repository at this point in the history
  • Loading branch information
alexmacarthur committed Mar 17, 2018
1 parent ccc296b commit d5423f3
Show file tree
Hide file tree
Showing 12 changed files with 1,261 additions and 176 deletions.
63 changes: 58 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ The Most Versatile JavaScript Animated Typing Utility on the Planet
* [Usage](#usage)
* [API](#api)
* [Options](#options)
* [Callback Methods](#callback-methods)
* [CodePen Examples](#codepen-examples)
* [Contribute](#contribute)
* [License](#license)
Expand Down Expand Up @@ -132,7 +133,13 @@ new TypeIt('.typeit-box', {
```

#### Companion Functions
To control a typewriter effect to the smallest character, pause, speed, or more, there companion functions available. Simply chain them together on an instance of TypeIt, and your chain will execute. You'll be able to create a dynamic, realistic narrative with just a few lines of code.
To control a typewriter effect to the smallest character, pause, speed, or more, there companion functions available. Simply chain them together on an instance of TypeIt, and your chain will execute. You'll be able to create a dynamic, realistic narrative with just a few lines of code that looks something like this:

```js
new TypeIt('#element', {
speed: 50
}).type('I want to type this.').pause(500).type('And type some more!');
```

| Function | Arguments | Description
| ------------- | ------------- | ------------- |
Expand Down Expand Up @@ -215,26 +222,32 @@ if(instance.isComplete) {
```

## Options
You can modify the options for the plugin by passing in JSON upon instantiation.
You can modify the options for the plugin by passing in JSON upon instantiation. It'll look something like this:

```js
new TypeIt('#element', {
strings: "Your default string.", // or, ["String #1", "String #2"]
speed: 100
})
```

| Option | Description | Default Value
| ------------- | ------------- | ------------- |
| strings | (string or array) The string(s) to be typed. | 'Your default string.' |
| speed | (number in millseconds) The typing speed. | 100 |
| deleteSpeed | (number in millseconds) The deletion speed. If left undefined, will be 1/3 of the type speed. | undefined |
| deleteSpeed | (number in millseconds) The deletion speed. If left null, will be 1/3 of the type speed. | null |
| lifeLike | (boolean) Will make the typing pace irregular, as if a real person is doing it. | true |
| cursor | (boolean) Show a blinking cursor at the end of the string(s). | true |
| cursorSpeed | (number in milliseconds) The blinking speed of the cursor. | 1000 |
| cursorChar | (string) The character used for the cursor. HTML works too! | pipe |
| breakLines | (boolean) Choose whether you want multiple strings to be printed on top of each other (`breakLines: true`), or if you want each string to be deleted and replaced by the next one (`breakLines: false`). | true |
| nextStringDelay | (number in milliseconds or array) The amount of time (milliseconds) between typing the next string when multiple strings are defined. You may either pass a number in milliseconds, or an array of values. The first value will be used as the delay before a new string starts, and the second value will be used as the delay after a string ends. For example, passing `[1000, 2000]` will tell TypeIt to pause 1000ms before typing a new string, and wait 2000ms after a string has just completed. | 750 |
| autoStart | (boolean) Defines if the instance start typing automatically, whatever is the position of the element in the viewport. Turn this option to `false` if you want to tell the instance to start typing only when the element reach the viewport. | true |
| autoStart | (boolean) Determines if the instance will typing automatically on page load, or only when the target element becomes visible in the viewport. If you don't want instances far down on the page to begin until they're visible, set this option to `false.` | true |
| startDelete | (boolean) Whether to begin instance by deleting strings inside element, and then typing what strings are defined via JSON or companion functions. | false |
| startDelay | (number in milliseconds) The amount of time before the plugin begins typing after initalizing. | 250 |
| loop | (boolean) Have your string or strings continuously loop after completing. | false |
| loopDelay | (number in milliseconds) The amount of time between looping over a string or set of strings again. | 750 |
| html | (boolean) Handle strings as HTML, which will process tags and HTML entities. If 'false,' strings will be typed literally. | true |
| callback | (function) A function that executes after your typing has completed. | nuthin' |

#### Changing Option Defaults
If you're creating several instances of TypeIt on a page, and don't wish to repeatedly set an option of the same value for each of them, you can redefine the default options beforehand. Change the default value(s) before creating any instances, and you'll be set.
Expand All @@ -248,6 +261,46 @@ new TypeIt('#id', {
});
```

## Callback Methods
Along all of these options, there are several callback method options you may use to trigger JavaScript at different points in time.

```js
new TypeIt('#id', {
strings: 'A string!'
afterString: function(step, queue, instance) {
//-- Execute your code here.
}
});
```

### Passed Arguments

Most callback methods will be passed the following arguments.

| Argument | Description
| ------------- | -------------
| step | Each character, deletion, pause, line break, etc. are "steps" in a queue of actions that are run with each instance. Each step is an array with the method that's called, an argument for the method, and a tag if it's the first or last character in a string that's been queued to be typed. So, a typical step will look something like this: `[Function type, 'm']`.
| queue | This is the rest of the queue that is yet to be typed. Each step in the queue is yet to be typed. Any steps that have already been typed will have been removed at this point.
| instance | The instance of TypeIt itself.

### Available Methods
Remember, each of these methods is passed as an option into your instance when you create it:

```js
new TypeIt('#id', {
afterString: function (step, queue, instance) {},
afterComplete: function (instance) {}
});
```

| Method | Description | Included Arguments
| ------------- | ------------- | ------------- |
| beforeString() | Before a new string is about to be typed. For example, if you pass two strings in an array when you set up TypeIt, this callback method will execute twice. | step, queue, instance |
| beforeStep() | Before each step in the queue is executed (including individual pauses, deletions, and new characters). | step, queue, instance
| afterString() | After a string is typed. | step, queue, instance
| afterStep() | After each step in the queue is executed. | step, queue, instance
| afterComplete() | After the entire instance is complete. This runs when all of the steps in the queue have been executed. So, technically, if you let the instance run out of steps and then add new steps later, this method could run more than once. | instance

## CodePen Examples
I have a few CodePen examples that illustrate how to do some interesting things with TypeIt.

Expand Down
137 changes: 95 additions & 42 deletions dist/typeit.es.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@
*
* typeit - The most versatile animated typing utility on the planet.
* Author: Alex MacArthur <alex@macarthur.me> (https://macarthur.me)
* Version: v5.5.2
* Version: v5.6.0
* URL: https://typeitjs.com
* License: GPL-2.0
*
*/
window.TypeItDefaults = {
strings: [],
speed: 100,
deleteSpeed: undefined,
deleteSpeed: null,
lifeLike: true,
cursor: true,
cursorChar: "|",
Expand All @@ -23,7 +23,12 @@ window.TypeItDefaults = {
loopDelay: 750,
html: true,
autoStart: true,
callback: function callback() {}
callback: false,
beforeString: false,
afterString: false,
beforeStep: false,
afterStep: false,
afterComplete: false
};

function isVisible(element) {
Expand Down Expand Up @@ -60,6 +65,29 @@ function toArray(string) {
return Array.isArray(string) ? string.slice(0) : string.split("<br>");
}

function groupHTMLTags(arr) {
var tPosition = [];
var tag = void 0;
var isEntity = false;

for (var j = 0; j < arr.length; j++) {
if (arr[j] === "<" || arr[j] === "&") {
tPosition[0] = j;
isEntity = arr[j] === "&";
}

if (arr[j] === ">" || arr[j] === ";" && isEntity) {
tPosition[1] = j;
j = 0;
tag = arr.slice(tPosition[0], tPosition[1] + 1).join("");
arr.splice(tPosition[0], tPosition[1] - tPosition[0] + 1, tag);
isEntity = false;
}
}

return arr;
}

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
Expand Down Expand Up @@ -101,9 +129,10 @@ var createClass = function () {
}();

var Instance = function () {
function Instance(element, id, options) {
function Instance(element, id, options, typeit) {
classCallCheck(this, Instance);

this.typeit = typeit;
this.timeouts = [];
this.id = id;
this.queue = [];
Expand Down Expand Up @@ -165,6 +194,7 @@ var Instance = function () {

this.cursor();
this.generateQueue();

this.kickoff();
}
}, {
Expand All @@ -181,16 +211,17 @@ var Instance = function () {
this.options.strings.forEach(function (string, index) {
_this.queueString(string);

//-- This is not the last string,so insert a pause for between strings.
if (index + 1 < _this.options.strings.length) {
if (_this.options.breakLines) {
_this.queue.push([_this.break]);
_this.insertSplitPause(_this.queue.length);
} else {
_this.queueDeletions(string);
_this.insertSplitPause(_this.queue.length, string.length);
}
//-- This is the last string. Get outta here.
if (index + 1 === _this.options.strings.length) return;

if (_this.options.breakLines) {
_this.queue.push([_this.break]);
_this.insertSplitPause(_this.queue.length);
return;
}

_this.queueDeletions(string);
_this.insertSplitPause(_this.queue.length, string.length);
});
}

Expand Down Expand Up @@ -248,10 +279,19 @@ var Instance = function () {
//-- Shorten it by one character.
string.splice(0, 1);

//-- If rake is true, this is the first time we've queued this string.
if (rake) {
this.queue[this.queue.length - 1].push("first-of-string");
}

//-- If there's more to it, run again until fully printed.
if (string.length) {
this.queueString(string, false);
return;
}

//-- End of string!
this.queue[this.queue.length - 1].push("last-of-string");
}

/**
Expand Down Expand Up @@ -374,11 +414,11 @@ var Instance = function () {
value: function pause() {
var _this3 = this;

var time = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var time = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

setTimeout(function () {
_this3.next();
}, time === null ? this.options.nextStringDelay.total : time);
}, time ? time : this.options.nextStringDelay.total);
}

/*
Expand All @@ -398,24 +438,7 @@ var Instance = function () {

//-- If we're parsing HTML, group tags into their own array items.
if (_this4.options.html) {
var tPosition = [];
var tag = void 0;
var isEntity = false;

for (var j = 0; j < item.length; j++) {
if (item[j] === "<" || item[j] === "&") {
tPosition[0] = j;
isEntity = item[j] === "&";
}

if (item[j] === ">" || item[j] === ";" && isEntity) {
tPosition[1] = j;
j = 0;
tag = item.slice(tPosition[0], tPosition[1] + 1).join("");
item.splice(tPosition[0], tPosition[1] - tPosition[0] + 1, tag);
isEntity = false;
}
}
return groupHTMLTags(item);
}

return item;
Expand Down Expand Up @@ -480,7 +503,7 @@ var Instance = function () {
key: "setPace",
value: function setPace() {
var typeSpeed = this.options.speed;
var deleteSpeed = this.options.deleteSpeed !== undefined ? this.options.deleteSpeed : this.options.speed / 3;
var deleteSpeed = this.options.deleteSpeed !== null ? this.options.deleteSpeed : this.options.speed / 3;
var typeRange = typeSpeed / 2;
var deleteRange = deleteSpeed / 2;

Expand All @@ -499,6 +522,7 @@ var Instance = function () {

var textArray = _this6.elementContainer.innerHTML.split("");

//-- Cut the array by a character.
for (var n = textArray.length - 1; n > -1; n--) {
if ((textArray[n] === ">" || textArray[n] === ";") && _this6.options.html) {
for (var o = n; o > -1; o--) {
Expand Down Expand Up @@ -565,7 +589,7 @@ var Instance = function () {
}

/*
Empty the existing text, clearing it instantly.
* Empty the existing text, clearing it instantly.
*/

}, {
Expand All @@ -585,13 +609,38 @@ var Instance = function () {

//-- We haven't reached the end of the queue, go again.
if (this.queue.length > 0) {
var thisStep = this.queue[0];
this.queue.shift();
thisStep[0].call(this, thisStep[1]);
this.step = this.queue.shift();

if (this.step[2] === "first-of-string" && this.options.beforeString) {
this.options.beforeString(this.step, this.queue, this.typeit);
}

if (this.options.beforeStep) {
this.options.beforeStep(this.step, this.queue, this.typeit);
}

//-- Execute this step!
this.step[0].call(this, this.step[1], this.step[2]);

if (this.step[2] === "last-of-string" && this.options.afterString) {
this.options.afterString(this.step, this.queue, this.typeit);
}

if (this.options.afterStep) {
this.options.afterStep(this.step, this.queue, this.typeit);
}

return;
}

this.options.callback();
//-- @todo: Remove in next major release.
if (this.options.callback) {
this.options.callback();
}

if (this.options.afterComplete) {
this.options.afterComplete(this.step, this.typeit);
}

if (this.options.loop) {
this.queueDeletions(this.elementContainer.innerHTML);
Expand All @@ -600,9 +649,11 @@ var Instance = function () {
setTimeout(function () {
_this7.next();
}, this.options.loopDelay / 2);
} else {
this.isComplete = true;

return;
}

this.isComplete = true;
}
}]);
return Instance;
Expand Down Expand Up @@ -646,7 +697,7 @@ var TypeIt = function () {
var _this = this;

[].slice.call(this.elements).forEach(function (element) {
_this.instances.push(new Instance(element, _this.id, _this.args));
_this.instances.push(new Instance(element, _this.id, _this.args, _this));
});
}
}, {
Expand Down Expand Up @@ -766,6 +817,8 @@ var TypeIt = function () {
}, {
key: "isComplete",
get: function get$$1() {
if (!this.instances.length) return false;

return this.instances[0].isComplete;
}
}]);
Expand Down
Loading

0 comments on commit d5423f3

Please sign in to comment.