Did you ever wish you could talk to individual letters in a string programmatically? You can with JavaScript/jQuery; you just have to know how to split strings.
Sample 1: Single-character hovering
This sample text turns red, character by character, when you hover over it with your mouse.
Sample 2: Letter-by-letter vanishing
This sample text vanishes, letter by letter, on a button click.
The secret to doing this is to split the string up into an array of individual <span> elements, which can then be styled individually.
How to split a string
function arrayMe(string) {
// For all matching elements
$(string).each(function() {
// Get contents of string
var myStr = $(this).html();
// Split myStr into an array of characters
myStr = myStr.split("");
// Build an html string of characters wrapped in tags with classes
var myContents = "";
for (var i = 0, len = myStr.length; i < len; i++) {
myContents += '<span class="single-char char-' + i + '">' + myStr[i] + '</span>';
}
// Replace original string with constructed html string
$(this).html(myContents);
});
}
// Calling arrayMe on page load, on class "sample-text"
$('document').ready(function() {
var myStringType = $('.sample-text');
arrayMe(myStringType);
});
The jQuery function above takes a selector as an argument, and splits the contents of all matching elements into individual, one-character <span> elements. The function then replaces the original string with a string of these one-character <span>s.
Each single-character <span> has two classes: single-char and char-i (where i is the character’s position in the original string).
Styling the individual characters
Sample 1:
.single-char:hover {
color:red;
cursor:pointer;
}
For the first demo, just add the style definition above to your CSS file.
Sample 2:
function vanish(selector) {
// If characters are already hidden, make them visible
if( $(selector).children('.single-char').css('visibility') == 'hidden' ) {
$(selector).children('.single-char').css('visibility','visible');
return false;
}
// Create an array of numbers corresponding to character indexes
var count = $(selector).children('.single-char').length;
var delOrder = new Array();
for(var i=0;i<count;i++) {
delOrder.push(i);
}
// Randomize the array so characters will disappear randomly
shuffle(delOrder);
// Set a counter to 0
var i = 0;
// Create a loop function
function myLoop () {
// Call a 30ms setTimeout when the loop is called
setTimeout(function () {
// Target a random character by class
var myClass = '.char-' + delOrder[i];
// Hide the class
$(selector).children(myClass).css('visibility','hidden');
// Increment the counter
i++;
if (i == delOrder.length ) {
// For the last iteration, replace button text
replaceButton();
}
// If the counter < array length, call the loop function
else {
// ...again which will trigger another
myLoop();
}
// ...setTimeout()
}, 30)
}
// Start the loop
myLoop();
}
The jQuery code above vanishes the individual characters, one by one, with a 30 millisecond delay between “vanish” events.
The code relies on an array shuffler function to randomize which letters disappear when, and a button listener to actually fire on button click.
Array shuffler
function shuffle(array) {
var counter = array.length, temp, index;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
index = Math.floor(Math.random() * counter);
// Decrease counter by 1
counter--;
// And swap the last element with it
temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
}
Button listener
function replaceButton() {
$('.vanish-button').html('Wait, come back!');
}
$('document').ready(function() {
$('.vanish-button').click(function() {
var myVanishType = $('.vanish-string');
var justHid = vanish(myVanishType);
if (justHid == false) {
$(this).html('Try it again');
}
});
});
Here’s a really cool text rainbow generator that works similarly. (We were going to build one, then found this.)
In response to Sample 1: Single-character hovering
I’m new to JavaScript/jQuery but the for loop does not seem to split each character into individual span elements with a class. All it does it put the split characters (done in the previous line with .split(”); back into a string stored in myContent.
Can you show me how you can split the characters into a span element with a class?
Great question! Believe it or not, that was our code previewer interpreting the <span> tag as an actual HTML <span>. Can’t tell you how many times I’ve had that issue in code tutorials.
Should be fixed now!