|
| 1 | +/** |
| 2 | + * @package birajrai/typer |
| 3 | + * @description Lightweight JavaScript plugin for adding nice, customizable typer effect using custom HTML5 attributes. |
| 4 | + * @author Awran5 <github.com/birajrai> |
| 5 | + * @version 1.0.0 |
| 6 | + * @license under MIT https://github.com/birajrai/typer/blob/main/LICENSE |
| 7 | + * @see <github.com/birajrai/typer> |
| 8 | + */ |
| 9 | + |
| 10 | + |
| 11 | +class typeWriting { |
| 12 | + |
| 13 | + constructor(element) { |
| 14 | + this.element = element; // Selector |
| 15 | + this.words = JSON.parse(element.getAttribute('data-words')); // Input words |
| 16 | + this.speed = parseInt(element.getAttribute('data-speed'), 10) || 100; // fallback 100 ms |
| 17 | + this.delay = parseInt(element.getAttribute('data-delay'), 10) || 1000; // fallback 1000 ms |
| 18 | + this.loop = element.getAttribute('data-loop'); |
| 19 | + this.char = ''; // word letters |
| 20 | + this.counter = 0; // loop counter |
| 21 | + this.isDeleting = false; // check when deleting letters |
| 22 | + this.type(); // Typing method |
| 23 | + } |
| 24 | + |
| 25 | + type() { |
| 26 | + // Set the words index. |
| 27 | + const index = this.loop === 'yes' ? this.counter % this.words.length : this.counter; |
| 28 | + // Get the full word |
| 29 | + const fullWord = this.words[index]; |
| 30 | + // Typing speed |
| 31 | + let typeSpeed = this.speed; |
| 32 | + |
| 33 | + if (this.isDeleting) { |
| 34 | + // Divide speed by 2 |
| 35 | + typeSpeed /= 2; |
| 36 | + // Add chars |
| 37 | + this.char = fullWord.substring(0, this.char.length - 1); |
| 38 | + } else { |
| 39 | + // Delete chars |
| 40 | + this.char = fullWord.substring(0, this.char.length + 1); |
| 41 | + } |
| 42 | + // Display on DOM |
| 43 | + this.element.innerHTML = `<span class="write">${this.char}</span><span class="blinking-cursor">|</span>`; |
| 44 | + // When word is completed |
| 45 | + if (!this.isDeleting && this.char === fullWord) { |
| 46 | + // break the loop before deletion. |
| 47 | + if (this.loop === "no" && this.counter >= this.words.length - 1) { |
| 48 | + return; |
| 49 | + } |
| 50 | + // Set char delete to true |
| 51 | + this.isDeleting = true; |
| 52 | + // Set time delay before new word |
| 53 | + typeSpeed = this.delay; |
| 54 | + } else if (this.isDeleting && this.char === '') { |
| 55 | + this.isDeleting = false; |
| 56 | + // Move to next word |
| 57 | + this.counter++; |
| 58 | + } |
| 59 | + // Set time out |
| 60 | + setTimeout(() => this.type(), typeSpeed); |
| 61 | + |
| 62 | + } |
| 63 | + |
| 64 | +} |
| 65 | + |
| 66 | +// Call the class on DOMContentLoaded |
| 67 | +document.addEventListener('DOMContentLoaded', init) |
| 68 | +// Select all elements and trigger the class |
| 69 | +function init() { |
| 70 | + document.querySelectorAll('.typewrite').forEach(e => new typeWriting(e)); |
| 71 | +} |
0 commit comments