:keyboard: Simulate a typewriter effect in vanilla JavaScript.

Overview

malarkey npm Version Build Status Coverage Status

Simulate a typewriter effect in vanilla JavaScript.

  • Flexible API allowing granular control
  • Option to repeat the sequence indefinitely
  • Allows stopping and resuming the sequence on-the-fly
  • 524 bytes gzipped

Usage

Editable demo (CodePen)

<div class="typewriter"></div>
const malarkey = require('malarkey')

const element = document.querySelector('.typewriter')
function callback (text) {
  element.textContent = text
}
const options = {
  typeSpeed: 50,
  deleteSpeed: 50,
  pauseDuration: 2000,
  repeat: true
}
malarkey(callback, options)
  .type('Say hello')
  .pause()
  .delete()
  .type('Wave goodbye')
  .pause()
  .delete()

API

const malarkey = require('malarkey')

const m = malarkey(callback [, options])

Initialise the typewriter effect with the given optional options settings.

  • callback is a function that is invoked for every type and delete event in the sequence. The function signature is (text), where text is the string of characters that have been typed so far.

  • options is an object literal:

    Key Description Default
    typeSpeed Duration in milliseconds to type a single character 50
    deleteSpeed Duration in milliseconds to delete a single character 50
    pauseDuration Duration in milliseconds to pause 2000
    repeat Whether to repeat the entire sequence indefinitely false

m.type(string [, options])

Type the given string, one character at a time.

  • Set options.speed to override the default typeSpeed.

m.delete([characterCount, options])

Delete the specified number of characters, one character at a time.

  • characterCount is a positive integer. If not specified, all characters previously typed will be deleted, one character at a time.
  • Set options.speed to override the default deleteSpeed.

m.pause([options])

Do nothing for some duration.

  • Set options.duration to override the default pauseDuration.

m.clear()

Immediately clear all characters that were typed.

m.call(fn)

Call the given fn function.

  • The function signature of fn is (callback, text). Invoke callback to signal that fn has finished execution and that we can move on to the next event in the sequence.

m.triggerStop([fn])

Stops the sequence. Calls the given fn function when the sequence has been stopped.

  • The function signature of fn is (text).

m.triggerResume()

Resume the sequence. Has no effect if the sequence is already running.

m.isStopped()

Returns true if the sequence is currently stopped, else returns false.

Installation

Install via yarn:

$ yarn add malarkey

Or npm:

$ npm install --save malarkey

License

MIT

Comments
  • Introduce valueGetter and valueSetter options

    Introduce valueGetter and valueSetter options

    I need to apply a typewriter effect to an input placeholder.. this generalization is perfectly backward compatible and makes the task trivial. Tests are all green!

    opened by stefanoverna 6
  • Expose immediate type and clear as semi-private API

    Expose immediate type and clear as semi-private API

    Adding the ability to bypass the queue system for advanced animations, particular case when you have two elements in the page that you want to sync, I couldn't find another way.

          const postTyper = malarkey(postEl, typerOptions);
          const receiveTyper = malarkey(receiveEl, {...typerOptions, loop: false});
    
          scope.vm.headlines.forEach((phrase) => {
            postTyper
              .call(function(el) {
                el.classList.add('has-cursor');
                this();
              })
              .type(phrase.post)
              .call(function(el) {
                el.classList.remove('has-cursor');
                receiveEl.classList.add('has-cursor');
                const self = this;
                receiveTyper._type(function() {
                  self();
                }, phrase.receive, typerOptions.typeSpeed);
              })
              .pause(1000)
              .call(function() {
                [postEl, receiveEl].forEach(elem => elem.classList.add('highlighted'));
                this();
              })
              .pause(1000)
              .call(function() {
                const self = this;
                [postEl, receiveEl].forEach(elem => {
                  elem.classList.remove('highlighted')
                  elem.classList.remove('has-cursor');
                });
                receiveTyper._clear(function() {
                  self();
                });
              })
              .clear()
    
    opened by xoredg 4
  • `delete(n)` is broken in version 1.0.1

    `delete(n)` is broken in version 1.0.1

    The following code worked fine on 0.0.2:

      malarkey(el, opts)
        .clear()
        .type(initialText).pause(pause).delete(initialWord.length)
        .type('browsers').pause(pause).delete(8)
        .type('angular').pause(pause).delete(7)
        .type('bower').pause(pause).delete(5)
        .type('gulp').pause(pause).delete(4)
        .type('browserify').pause(pause).delete(10)
        .type('grunt').pause(pause).delete(5)
        .type('tessel').pause(pause).delete(6)
        .type('JavaScript').pause(pause)
        .type('.');
    

    but when I installed 1.0.1, I see strange behavior. Instead of deleting the specified number of characters, it's deleting all characters in the element (incrementally, not all at once).

    The real code is here: https://github.com/npm/newww/blob/b6206de7972714f69b17dfae053ad3ffd5dfba12/assets/scripts/what-npm-is-for.js#L19-L31

    opened by zeke 3
  • Publish latest to npm

    Publish latest to npm

    Hi @yuanqing.

    I love this package. Thanks for creating it. I'm hoping to use it on the new npm website.

    Can you publish the latest version to npm?

    Thanks!

    opened by zeke 3
  • Add an `end` handler

    Add an `end` handler

    I want to call a function after everything is done:

    malarkey(el, {})
      .type("foo").pause(1000).delete()
      .type('bar').pause(1000).delete()
      .end(function(el) {
        console.log(el.classList.remove("typing"))
      })
    

    @yuanqing if you see an easy way to add this, I'd be grateful. Otherwise I can give it a try myself. :)

    opened by zeke 2
  • karma.conf.js does not exist

    karma.conf.js does not exist

    I have npm installed successfully, but when I run gulp I get this error:

    malarkey* master » gulp
    [22:20:53] Using gulpfile ~/code/forks/malarkey/gulpfile.js
    [22:20:53] Starting 'lint'...
    [22:20:53] Starting 'clean'...
    [22:20:53] Finished 'clean' after 18 ms
    [22:20:53] Starting 'dist'...
    [22:20:53] Finished 'lint' after 112 ms
    [22:20:54] Finished 'dist' after 380 ms
    [22:20:54] Starting 'test'...
    ERROR [config]: File /Users/z/code/forks/malarkey/test/karma.conf.js does not exist!
    
    opened by zeke 2
  • try fixing &-deleting bug

    try fixing &-deleting bug

    Using textContent instead of innerHTML fixes the bug when deleting HTML entities.

    However, textContent raises the browser compatibility to IE9. An alternative is to use innerText which, however, ignore trailing white spaces, so more checks should be done.

    opened by gigaflw 1
  • Annoying flickering when delete

    Annoying flickering when delete

    There is a some annoying flickering effect when element content deletes. I prepared codepen for you. It can be easy fixed by css:

    .malarkey {
        min-height: 20px;
    }
    

    But is it possible to implement this feature out of the box? Thank you.

    opened by EvgeniyRRU 1
  • Script can't remove content with '&'

    Script can't remove content with '&'

    If I insert the content 'Soda & Beers', the script won't be able to remove the content before & and hence 'Soda &' will get appended again and again. Here is an example: 'Soda & Soda & Soda & Beers'

    bug help wanted 
    opened by karankashyap 1
  • Doesn't type out HTML

    Doesn't type out HTML

    malarkey.type('<strong>Hi</strong>'); literally types out <strong>Hi</strong>. Is it possible to write it out as a DOM element?

    opened by danyim 1
  • Highlight feature

    Highlight feature

    Would it be possible to have a highlight-then-delete feature for the word that is typed? Hubspot.com has this. The effect makes it looks like someone is highlighting the word that was typed and then deleting it.

    opened by amit777 1
  • ES Modules

    ES Modules

    It would be nice if this was available as an es module.

    If you like, I'll make a PR which refactors to es6 and esm, and I'll add rollup to transform to cjs and minify

    opened by bennypowers 0
Owner
Yuan Qing Lim
Designer/Software Engineer
Yuan Qing Lim
fakeLoader.js is a lightweight jQuery plugin that helps you create an animated spinner with a fullscreen loading mask to simulate the page preloading effect.

What is fakeLoader.js fakeLoader.js is a lightweight jQuery plugin that helps you create an animated spinner with a fullscreen loading mask to simulat

João Pereira 721 Dec 6, 2022
Native typewriter effect, without compromises or dependencies.

T-Writer.js Native typewriter effect, without compromises or dependencies. See a demo for ideas/examples. Why Creating a custom typewriter effect can

Christopher Cavalea 508 Dec 1, 2022
The typewriter effect

#No documentation yet! (feel free to write a bit about it) Download Get the raw script, download the complete package or fork it on GitHub. Support @y

Yannick Albert 27 Oct 7, 2020
A phaser helper for the typewriter effect

Phaser-typewriter A typewriter effect wrapper for Phaser.io Javascript library Initialize the typewriter anywhere in your game var typewriter = new Ty

Michael Dobekidis 39 Jul 27, 2022
A basic Typewriter effect.

Remotion video A basic Typewriter template. video.mp4 Commands Install Dependencies npm i Start Preview npm start Render video npm run build Upgrade R

Remotion 14 Dec 6, 2022
⌨️ Lightweight $.Hypertext.Typewriter

⚠️ iOS 13.3 note (April 2020) beep[:true] freezes the typewriter, read more: issue #11 Nice features ?? full HTML support beep-beep Hypertypin' Markup

Benjamin Lips 309 Dec 22, 2022
Liquideffect - Javascript Library for creating liquid effect on image and RGB effect on mouse direction.

LiquidEffect Javascript Library for creating liquid effect on image and RGB effect on mouse direction. Demo https://liquideffect.netlify.app/ Dependen

Rohail 8 May 6, 2022
Cool and powerful effect to select fields. Javascript vanilla and ~2kb gzipped

pickout Cool and powerful effect to select fields. Javascript vanilla and ~2kb gzipped. DEMO PAGE For syntax of the previous version click here How to

Alan Ktquez 89 Sep 20, 2022
A subtle tilt effect for images. The idea is to move and rotate semi-transparent copies with the same background image in order to create a subtle motion or depth effect.

Image Tilt Effect A subtle tilt effect for images. The idea is to move and rotate semi-transparent copies with the same background image in order to c

Codrops 571 Nov 21, 2022
Javascript library enabling magnifying glass effect on an images

Magnifier.js Javascript library enabling magnifying glass effect on an images. Demo and documentation Features: Zoom in / out functionality using mous

Mark Rolich 808 Dec 18, 2022
"shuffle-text" is JavaScript text effect library such as cool legacy of Flash.

ShuffleText This is the JavaScript library for text effect such as Flash contents. Setup Script Install <script src="shuffle-text.js"></script> NPM In

Yasunobu Ikeda 96 Dec 24, 2022
Enterprise-grade JavaScript snow effect for the internets, setting CPUs on fire worldwide every winter since 2003.

/** * DHTML Snowstorm! JavaScript-based Snow for web pages * -------------------------------------------------------- * Version 1.44.20131208 (Prev

Scott Schiller 518 Dec 24, 2022
Small but good javascript smoke effect 🌬💨

Demo You can play with a live demo here → Installation Basic Copy the smoke.js file into your project and use it with a script tag: <script src="smoke

Guillermo Webster 239 Dec 28, 2022
Javascript and SVG odometer effect library with motion blur

SVG library for transitioning numbers with motion blur JavaScript odometer or slot machine effect library for smoothly transitioning numbers with moti

Mike Skowronek 793 Dec 27, 2022
Javascript Sound Effect Generator

This is a JavaScript library for sound effect generation and is supported on most current browsers. Generation speed is approximately 1s audio = 10ms

Loov 567 Oct 31, 2022
🎨 Aquarelle is a watercolor effect component. Javascript library by @Ramotion

Aquarelle About This project is maintained by Ramotion, Inc. We specialize in the designing and coding of custom UI for Mobile Apps and Websites. Look

Ramotion 1.8k Dec 9, 2022
Add a water ripple effect to your background using WebGL.

jQuery Ripples Plugin By the powers of WebGL, add a layer of water to your HTML elements which will ripple by cursor interaction! Important: this plug

Pim Schreurs 976 Dec 30, 2022
A decorative website background effect where SVG shapes morph and transform on scroll.

Morphing Background Shapes A decorative website background effect where SVG shapes morph and transform on scroll. Article on Codrops Demo This demo is

Codrops 351 Dec 26, 2022
Background image segment effect as seen on [Filippo Bello's Portfolio](http://www.filippobello.com/portfolio).

Segment Effect Background image segment effect as seen on Filippo Bello's Portfolio. Article on Codrops Demo License Integrate or build upon it for fr

Codrops 526 Nov 29, 2022