Skip to content

Commit

Permalink
Add method to destroy instance on respective elements.
Browse files Browse the repository at this point in the history
  • Loading branch information
alexmacarthur committed Dec 8, 2017
1 parent 64644f5 commit a4811c0
Show file tree
Hide file tree
Showing 5 changed files with 104 additions and 37 deletions.
44 changes: 34 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ The Most Versatile JavaScript Animated Typing Utility on the Planet
- [Overview](#overview)
- [Choose a License](#choose-a-license)
- [Usage](#Usage)
- [API](#api)
- [Options](#options)
- [Contribute](#contribute)
- [License](#license)
Expand Down Expand Up @@ -99,18 +100,11 @@ For example:
.type('t!');
```

### Companion Functions
To view these functions and how they work, see the [API](#api) section.

| Function | Arguments | Description
| ------------- | ------------- | ------------- |
| type() | (string) Characters (including those wrapped in HTML) to be typed. | Will type the characters. |
| delete() | (number) Number of characters to be deleted from what's already been typed. | Will delete the specified number of characters. |
| empty() | (none) | Will instantly delete everything that has already been typed.
| pause() | (number) Number of milliseconds to pause before continuing. | Will pause the specified number of milliseconds.|
| break() | (none) | Will break the typing to a new line.|
| options() | (JSON) Options you'd like to update | Will redefine your options on the fly. This will only work for updating the `speed`, `lifeLike`, and `html` options.|
## API

## Options
### Options

You can modify the options for the plugin by passing in JSON.

Expand All @@ -133,6 +127,36 @@ There are a number of options you may use to customize TypeIt. For more details
| 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' |

### Companion Functions

Use these functions to chain typing commands together upon initialization.

| Function | Arguments | Description
| ------------- | ------------- | ------------- |
| type() | (string) Characters (including those wrapped in HTML) to be typed. | Will type the characters. |
| delete() | (number) Number of characters to be deleted from what's already been typed. | Will delete the specified number of characters. |
| empty() | (none) | Will instantly delete everything that has already been typed.
| pause() | (number) Number of milliseconds to pause before continuing. | Will pause the specified number of milliseconds.|
| break() | (none) | Will break the typing to a new line.|
| options() | (JSON) Options you'd like to update | Will redefine your options on the fly. This will only work for updating the `speed`, `lifeLike`, and `html` options.|

### Other Handy Functions

#### Destroy an Instance

| Function | Arguments | Description
| ------------- | ------------- | ------------- |
| destroy() | (bool) Whether you want to remove the cursor after destroying. Default is `true`.| Destroys the instance on whatever elements to which it's attached.

```js
var instance = new TypeIt('#id', {
strings: 'This is my string'
});

//-- Will preserve the cursor. If you want to destory that too, pass 'false'.
instance.destroy();
```

## Contribute

Please do! The code is available on Github. Check out the [CONTRIBUTING.md](CONTRIBUTING.md) file to see how to get started.
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "typeit",
"version": "5.0.2",
"version": "5.1.0",
"description": "The most versatile animated typing utility on the planet.",
"author": "Alex MacArthur <[email protected]> (https://macarthur.me)",
"license": "GPL-2.0",
Expand Down
29 changes: 9 additions & 20 deletions src/instance.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export default class Instance {
constructor(element, options) {
constructor(element, id, options) {
this.defaults = {
strings: [],
speed: 100,
Expand All @@ -18,7 +18,8 @@ export default class Instance {
callback: function() {}
};

this.id = "";
this.timeouts = [];
this.id = id;
this.queue = [];
this.queueIndex = 0;
this.hasStarted = false;
Expand Down Expand Up @@ -48,7 +49,6 @@ export default class Instance {
this.style +
' class="ti-container"></span>';

this.id = this.generateHash();
this.element.setAttribute("data-typeitid", this.id);
this.elementContainer = this.element.querySelector("span");

Expand Down Expand Up @@ -144,33 +144,22 @@ export default class Instance {
return true;
}

generateHash() {
return (
Math.random()
.toString(36)
.substring(2, 15) +
Math.random()
.toString(36)
.substring(2, 15)
);
}

cursor() {
if (!this.options.cursor) return;

let hash = this.generateHash();

let styleBlock = document.createElement("style");

styleBlock.id = this.id;

let styles = `
@keyframes blink-${hash} {
@keyframes blink-${this.id} {
0% {opacity: 0}
49%{opacity: 0}
50% {opacity: 1}
}
[data-typeitid='${this.id}'] .ti-cursor {
animation: blink-${hash} ${this.options.cursorSpeed /
animation: blink-${this.id} ${this.options.cursorSpeed /
1000}s infinite;
}
`;
Expand Down Expand Up @@ -299,7 +288,7 @@ export default class Instance {
string = string[0];
}

this.typingTimeout = setTimeout(() => {
this.timeouts[0] = setTimeout(() => {
//-- Randomize the timeout each time, if that's your thing.
this.setPace(this);

Expand Down Expand Up @@ -400,7 +389,7 @@ export default class Instance {
}

delete(chars = null) {
this.deleteTimeout = setTimeout(() => {
this.timeouts[1] = setTimeout(() => {
this.setPace();

let textArray = this.elementContainer.innerHTML.split("");
Expand Down
39 changes: 34 additions & 5 deletions src/typeit.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import Instance from "./instance";

export default class TypeIt {
constructor(element, options) {
this.elements = [];
constructor(element, args) {
this.id = this.generateHash();
this.instances = [];
this.elements = [];
this.args = args;

if (typeof element === "object") {
//-- There's only one!
Expand All @@ -20,12 +22,23 @@ export default class TypeIt {
this.elements = document.querySelectorAll(element);
}

this.createInstances(options);
this.createInstances();
}

generateHash() {
return (
Math.random()
.toString(36)
.substring(2, 15) +
Math.random()
.toString(36)
.substring(2, 15)
);
}

createInstances(options) {
createInstances() {
[].slice.call(this.elements).forEach(element => {
this.instances.push(new Instance(element, options));
this.instances.push(new Instance(element, this.id, this.args));
});
}

Expand All @@ -40,6 +53,22 @@ export default class TypeIt {
return this;
}

destroy(removeCursor = true) {
this.instances.forEach(instance => {
instance.timeouts.forEach(timeout => {
clearTimeout(timeout);
});

if (removeCursor) {
instance.element.removeChild(
instance.element.querySelector(".ti-cursor")
);
}
});

this.instances = [];
}

delete(numCharacters) {
this.pushAction("delete", numCharacters);
return this;
Expand Down
27 changes: 26 additions & 1 deletion tests/typeit.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,30 @@ test('Returns an object with base properties.', () => {

const instance = new TypeIt('#element', {});

expect(Object.keys(instance).sort()).toEqual(['elements', 'instances'].sort());
expect(Object.keys(instance).sort()).toEqual(['elements', 'id', 'instances', 'args'].sort());

document.body.innerHTML = '';
});

test('Destroys instances successfully.', () => {

jest.useFakeTimers();

document.body.innerHTML =
`<div>'
<span id="element"></span>
</div>`;

const instance = new TypeIt('#element', {
strings: 'This is my string!'
});

jest.runAllTimers();

instance.destroy();

expect(instance.instances).toHaveLength(0);
expect(document.body.querySelector('.ti-cursor')).toEqual(null);

document.body.innerHTML = '';
});

0 comments on commit a4811c0

Please sign in to comment.