JavaScript
Article

Animating Text with Blast.js

By Jérémy Heleine

Animating an HTML element with CSS or JavaScript nowadays, with the help of libraries, is more or less an easy task. But you can only animate a full existing element.

This means if you want to animate a single word in a paragraph, you have to wrap the word in an individual element (like a span) and then target it accordingly.

If you have only one or two span elements like this, it is not a big deal, but what if you want to animate each character in a paragraph? For every character, you will have to create a span, which adds a lot of extra markup and makes the text difficult to edit. That’s why Blast.js exists.

What is Blast.js?

Blast.js is a jQuery plugin that allows you to animate individual characters, words, or sentences. In this article, I will present some examples so you can see how to use Blast.js. To use Blast.js and try the examples below, you will need jQuery and of course the Blast.js file, which can be found on the project website for Blast.js.

As mentioned, Blast.js lets us create elements around characters, words, or sentences, but the library isn’t only limited to those options. In the next section, we will see some concrete examples to introduce some options. The list of options we will see is not exhaustive; the full list of available options can be found on the project’s website.

Blasting our First Chunk of Text

In this first example, we will blast a title to animate each character and move them, one by one, to the right. The only HTML code needed is the following:

<h1>Hello World!</h1>

After including jQuery and Blast.js, the next bit of code in this part will all be in your custom JavaScript file inside of jQuery’s ready handler, to ensure the page is ready:

$(function() {
  // Animation code
});

Now we can blast our title. In our example, just using $('h1') to target the element will be enough, but in your case you’ll use whatever selector is appropriate to target the element.

Blast.js offers a new method on the jQuery object: .blast(), which takes one parameter: an object listing all options you want to use. In this first example, we will use only one option, delimiter: 'character', to indicate that we want to blast our title character by character.

If we hadn’t included the parameter, the default value 'word' would be used (instead of “character”, so a span would be created around each word (and not around each character as we want here).

$('h1').blast({
  delimiter: 'character'
});

With this, our simple h1 element will be blasted and will result in the following generated DOM:

<h1 class="blast-root">
  <span class="blast">H</span>
  <span class="blast">e</span>
  <span class="blast">l</span>
  <span class="blast">l</span>
  <span class="blast">o</span>

  <span class="blast">W</span>
  <span class="blast">o</span>
  <span class="blast">r</span>
  <span class="blast">l</span>
  <span class="blast">d</span>
  <span class="blast">!</span>
</h1>

Note that the space between the words has been preserved and has not been encapsulated into a span.

Now, we need to retrieve the generated span elements. You could try $('.blast') for example, but there is a simpler way. By default, the .blast() method returns the generated elements, so that the only thing you have to do to retrieve these elements is store them in a variable.

var chars = $('h1').blast({
  delimiter: 'character'
});

Getting the generated elements is useful, but not all the time. So, if you want the .blast() method to return the parent element (the main one you are blasting) rather than the generated ones, this can be done with another option: returnGenerated. By default, it is set to true; set it to false and you will have your parent element:

var chars = $('h1').blast({
  delimiter: 'character',
  returnGenerated: false
});

Let’s return to our example to animate the elements we’ve collected. We will animate each character, one by one, thanks to jQuery’s .each() method.

The .each() method will execute a function for each element stored in a jQuery object. Here is the one we will use, explained in the comments.

// A character by character animation
chars.each(function(i) {
  // initialize position
  $(this).css({
    position: 'relative',
    left: 0
  })

  // Delay: we don't want to animate
  // characters simultaneously
  .delay(i * 45)

  // Animate to the right
  .animate({ left: '50px' }, 300);
});

To explain the code: First, we retrieve the current element (i.e. the current character in our case) using $(this). We initialize its relative position to zero and, finally, we animate this position.

As stated in the corresponding comment in the code, the .delay() method launches the animation after a defined number of milliseconds, using i * 45, where i is a counter provided by jQuery (which we pass in as a parameter). For the first character, i is equal to 0, so the animation is launched immediately, then it is equal to 1 and the second character is animated after 45 milliseconds, and so on.

Our animation is ready, and it works! You can view a live example below.

See the Pen Blast.js example by SitePoint (@SitePoint) on CodePen.

Choose Your Wrapping Element

By default, span elements are created and that’s what we’ll want most of the time. But sometimes we would like to play with other elements such as strong, em, or even div and p. With Blast.js this is possible.

To do that, for our next example we’ll make a paragraph in which each word will be stylized with a random color and encapsulated in an em element.

First we need a function to provide us a random number. We’ll use a modified version of Math.random() available in native JavaScript.

function rand(min, max) {
  return parseInt(Math.round(min + Math.random() * (max - min)));
}

This new function will give us a random integer between min and max, the arguments passed into the function.

Now we are ready to color our paragraph. First we blast our paragraph using the delimiter 'word'. We add a new option: tag, which allows us to indicate the tag we want Blast.js to use to generate elements. Instead of the default 'span' we will set it to 'em'.

var words = $('p').blast({
  delimiter: 'word',
  tag: 'em'
});

Now all our words are encapsulated inside em tags. For each tag, we define a new color thanks to jQuery’s .css() method and our custom rand() function:

words.each(function() {
  $(this).css('color', 
              'rgb(' + rand(0, 255) + ',
              ' + rand(0, 255) + ',
              ' + rand(0, 255) + ')');
});

Next we will add another line of code to introduce how to retrieve the initial state of our parent element (i.e. how to remove all these extra generated tags).

To do this, you can give the value false to the .blast() method. This tells Blast.js that all the tags added with previous calls to this method will be removed.

You can view a live version of this example below.

See the Pen Blast.js Colors demo by SitePoint (@SitePoint) on CodePen.

Note that applying the .blast(false) method to an element which has not been transformed by Blast.js will do nothing.

Searching with Blast.js

By default, Blast.js will create elements around every word, character, or sentence in your text. But you can also target only one word or one group of words: Blast.js will then encapsulate each occurrence of the word or group of words into an element. To do that, we use the search option with a string as value, instead of the delimiter option.

To demonstrate, we will create a form containing an input and a submit button. The user will indicate in the input the word to search in a specific paragraph, and Blast.js will then encapsulate the searched terms into span elements.

<form method="get" action="search.html">
    <p>
      <input type="text" name="s" id="s" placeholder="Search">
      <input type="submit" value="Go!">
    </p>
</form>

We will use the submit event on our form to execute this.

$('form').submit(function(e) {
  $('#awesometext').blast(false).blast({
    search: $('#s').val(),
    customClass: 'search',
    generateIndexID: true
  });

  e.preventDefault();

});

The instruction e.preventDefault(); is included to disable the default behavior of the form, which is to submit the form.

We retrieve our paragraph with the right selector before applying the .blast() method the first time with the false value. That way, if the user previously performed other searches, these will be cleared.

Next we use the .blast() method again, this time to search the wanted term. To do that, we use the search option, giving it the value of the input. The two other options are not mandatory, but they can be useful and I wanted to show you that they exist.

The customClass option allows us to add our own class name to the generated elements. If you looked at the generated elements in the previous examples, you surely saw that they all have the blast class. With customClass, you can add one or more classes.

The generateIndexID option is a Boolean. Set to true, it will add an ID to each generated element. To work, it needs the use of the customClass option. Here, we chose the class search, so the first generated element will have the ID search-1, the second one will have search-2, etc.

In order to make our example useful, we need to add some rules in the CSS to highlight the generated elements. For example, you can apply the following rules.

.search {
  background-color: #0096ff;
  color: #fff;
}

#search-1 {
  font-weight: bold;
}

You can view a live version of this example below. Try typing one of the existing words shown on the page to see the effect.

See the Pen Blast.js Search example by SitePoint (@SitePoint) on CodePen.

What About Existing Elements?

There is an important question to answer now that we’ve seen how Blast.js works. Since we apply the .blast() method to a container, what if this container already contains some elements other than text nodes? For example, what happens if we apply a blast to the following paragraph?

<p>Hello <span>World</span>!</p>

Blast.js won’t break your DOM tree. In this case, the existing span element won’t be removed, and a new one (with the blast class) will be created. By executing $('p').blast() on the above paragraph, we generate the following result:

<p class="blast-root">
  <span class="blast">Hello</span>

  <span>
    <span class="blast">World</span>
  </span>
  <span class="blast">!</span>
</p>

Finally: what if this existing span elements is actually a span generated by Blast.js? The answer depends on what you want to do.

Assuming that we’ve applied the .blast() method to a paragraph with the delimiter option set to 'word', if we apply the same method again, the previous generated elements will be removed before creating the new ones, even if the new call uses a search instead of a delimiter.

However, if you searched a term, and call the .blast() method again to search a new term, the old search won’t be removed. In our last example of the previous part, try to remove the .blast(false) call. In such a case, new searches will be highlighted, but the old ones will stay highlighted too.

In Conclusion

Blast.js won’t be useful for everyone, and some might view it as completely unnecessary. But if you want to animate text, this might be one of the best options you can find.

As said above, you can find other options to customize the generated elements. You can even disable the ARIA attributes if you choose.

If you have any thoughts on how this can be used in a creative way, or if you’ve used this or another tool to animate text, feel free to let us know in the discussion.

Comments
dathan_n

I think the proper way to animate text is to use DOM to calculate the flow, convert DOM > SVG > Canvas. I think only IE8 wouldn't support it.

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.