O'Reilly

MooTools Typewriter Effect Plugin Upgrade

By on  

Last week I shared my MooTools Typewriter Class with you. It was pretty well received and I got a few feature requests that I've implemented including "backspacing" and character variance delays. I'm not going to explain the old code, so click here to get the full explanation on the class.

MooTools 1.2 Class

//class is in
var Typewriter = new Class({
	
	//implements
	Implements: [Options],

	//options
	options: {
		container: $$('body')[0],
		message: '',
		delay: 150,
		cursor: 0,
		variance: 0,
		backChar: '|',
		backDelay: 30
	},
	
	//initialization
	initialize: function(options) {
		//set options
		this.setOptions(options);
	},
	
	//start the Typewriter
	start: function() {
		
		//for every letter
		for(x = 0; x < this.options.message.length; x++)
		{
			var pace = (this.options.delay * x) + $random(0,this.options.variance);
			var current = this.options.message.charAt(x);
			
			//spit out the letter
			if(current != this.options.backChar)
			{
				var go = this.setLetter.delay(pace,this);
			}
			else
			{
				var go = this.deleteLetter.delay(pace + this.options.backDelay,this);
			}
			
		}
	},
	
	//place the newest letter in the container
	setLetter: function() {
		
		this.options.container.set('html',this.options.container.get('html') + '' + this.options.message.charAt(this.options.cursor));
		
		//increment cursor
		this.options.cursor++;
	},
	
	//deletes a letters -- goes backward
	deleteLetter: function() {
		
		this.options.container.set('html',this.options.container.get('html').substr(0,this.options.container.get('html').length - 1));
		
		//increment cursor
		this.options.cursor++;
	}
	
});

MooTools Usage

var t = new Typewriter({
	container: $('type-here'),
	message: 'This is output from the Typewriter class. This class is small but packs a really good|||||||||||SUPER HUGE punch. Isn\'t MooTools great?',
	delay:90,
	variance:200,
	backChar: '|',
	backDelay:30
}).start();

You'll see three new options:

  • variance: No one types at the same speed for every letter. Variance allows for random letter delay changes.
  • backChar: Which character signifies a backspace?
  • backDelay: How quickly should the typewriter delete?

Click here to view the new version.

O'Reilly Velocity Conference
Save 20% with discount code AFF20

Recent Features

  • An Interview with Eric Meyer

    Your early CSS books were instrumental in pushing my love for front end technologies. What was it about CSS that you fell in love with and drove you to write about it? At first blush, it was the simplicity of it as compared to the table-and-spacer...

  • Animated 3D Flipping Menu with CSS

    CSS animations aren't just for basic fades or sliding elements anymore -- CSS animations are capable of much more.  I've showed you how you can create an exploding logo (applied with JavaScript, but all animation is CSS), an animated Photo Stack, a sweet...

Incredible Demos

  • Control Element Outline Position with outline-offset

    I was recently working on a project which featured tables that were keyboard navigable so obviously using cell outlining via traditional tabIndex=0 and element outlines was a big part of allowing the user navigate quickly and intelligently. Unfortunately I ran into a Firefox 3.6 bug...

  • Unicode CSS Classes

    CSS class name structure and consistency is really important; some developers camelcase classnames, others use dashes, and others use underscores.  One thing I've learned when toying around by HTML and CSS class names is that you can actually use unicode symbols and icons as classnames....

Discussion

  1. Catar4x

    It works with the mootools 1.2dev version ?
    I will try this upgrade but the first doesn’t works.
    It’s perhaps my other scripts that fail the implementation of the code.

  2. Keep in mind that so much setTimeouts slows down everything. Maybe you should try creating an Fx with a transition to make that variance effect, that way you’ll use one setInterval instead of 100+ setTimeouts simultaneously.

    Other than that, very nice thingy!

  3. Would be nice if it could loop through x amount strings and continue looping.

    Is .periodical() the only way this can be done since since time cannot be calculated due to the speed variance?

    Surely someone knows a better way to loop function simultaneously after completion?

    I will have a go at it myself.

  4. One idea I have would be to use the existing text in the container, for instance rather than having to use the “message:” option in javascript, I would like to have the text already in the container.

  5. Yeah I have done that. All the text is already in the container and hidden. And I have added a small bit of code that then splits the text into an array and removes the hidden style/class.

    I’m just having trouble getting it to loop.

  6. OK I have finally managed to modify this script so that it can rotate through multiple messages.

    I took Leo Newballs comment on-board and fi there’s already a string in the container you specify in the options, it overrides the default message with this string and splits it into an array.

    If backChar is specified in the options, It randomly injects a character, or a block of characters(major typo) and cuts it into a random position within your string so it looks like authentic typing (i hope) and then deletes them.

    Does anyone fancy testing it?

  7. I love testing new items! I would love to give it a go!

  8. How will i send the code? Shall I just post it on here?

  9. Send you a message through your contact page Liam :-D

  10. tamamma

    Hi there, first of all thank you for everything. This website is very useful.
    I would like to know if there is the possibility to insert any html tag for a part of the text of the typewriter(for example bold or ecc) it would be very nice!!
    Thank you again

  11. @tamamma: Adding HTML in the message is not possible since the typewriter goes character by character. You would want to create something more advanced.

  12. Steve

    Firstly I’d like to echo the “thank you for everything”, this is perfect for what i’m working on except I need to be able to insert line breaks, any ideas on a simple way to go about this?

  13. @Steve: Sorry, this wasn’t set up for that. You could, however, add a special charachter into your string (like a “*”), and in the start() or setLetter() methods check for, and add a “
    ” instead of the special character.

  14. Same answer as the previous question.

    @tamamma: Adding HTML in the message
    is not possible since the typewriter
    goes character by character. You would
    want to create something more
    advanced.

  15. chris

    Is there any way to reset the text on an event? i.e. ‘mouseleave’

    I need it to function in a similar way to the Fx chain property –
    e.g. chain:cancel etc.

    At the moment I have the text appearing under each icon on a menu when ‘mouseenter’ occurs, with a simple element level text reset on ‘mouseleave’. However this causes some odd results when the Typewriter effect hasn’t finished ‘typing’ before the mouse moves off and then back on again, or onto another!

    Great work btw.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • Prevent Chrome from Translating a Page

    A while back I shared my favorite Google Chrome extension:  Google Art Project.  I've enjoyed seeing beautiful art when I open a new tab -- it's brought genuine happiness to my day, however small that happiness may be.  About a week ago, however, the art presented had...

  • Create Any Type Of Website With These Multi-Purpose Themes

    We have selected what we believe are the very best multipurpose WordPress themes on the market today. Our list contains a number of best sellers, several newcomers that are proving to be highly popular, and a few themes that are ideal for creating the types of...

  • An Introduction to Static Site Generators

    Static site generators seem to have been becoming more and more popular recently, but they’re not one of those ephemeral novelty things that grow in popularity as quickly as they fall into oblivion shortly after. For over a decade, many different projects — 394 of...

  • Automated Tests for Visual Responsive Layouts

    Today it's all about testing. In 2015, many developers knows about TDD and I personally think that testing is one of the key for quality products. But what about testing in a Front-end environment? How do you guys write your tests for a responsive page or...

  • Getting Dicey With Flexbox

    What if you could build complex CSS layouts in minutes? Flexbox is a new CSS layout spec that makes it easy to construct dynamic layouts. With flexbox, vertical centering, same-height columns, reordering, and direction agnosticism are a piece of cake. There's a popular myth floating around that...