Before you begin
This tutorial requires InstantSearch.js.High-level overview
To create an animated placeholder, you want to run some code that animates text character by character with pauses between, and injects it into the search box as placeholder text. The length of a pause should be random so it looks like actual typing. The recommended delay range of 50-90 milliseconds looks the most natural.Single placeholder
1
Add a search box
Add an InstantSearch
searchBox widget and set its placeholder to an empty string.JavaScript
2
Declare constants
Declare the following constants:
- The search box element
- The delay after the animation has run
- The animation delay between letters (a minimum and maximum value)
- Your placeholder text.
JavaScript
3
Randomize animation time
Add a function that returns a random integer between a minimum and maximum value. This gets the animation time for each letter.
JavaScript
4
Set the placeholder attribute value
Add a function that sets the value of the placeholder attribute in the search box.
JavaScript
5
Animate the characters
-
Add a function that recursively animates all the characters from an array.
JavaScript
-
Add a function that makes the initial call to
animateLetters.JavaScript
6
Animate the placeholder
Add an event listener that animates the placeholder when the page loads.
JavaScript
Multiple placeholders
To animate multiple placeholders, you need to make a few changes to the code you wrote for a single placeholder implementation.1
Change placeholder constant
Change your
PLACEHOLDER constant to an array of strings called PLACEHOLDERS,
containing all the placeholder sentences you want to display.JavaScript
2
Select random placeholder
-
Add an
onAnimationEndcallback function that selects a random (but different) placeholder string from yourPLACEHOLDERSarray and calls theanimatePlaceholderfunction with the new string. This function triggers every time the animation ends.JavaScript -
Change the return value of your
animateLetterfunction so that it calls theonAnimationEndfunction whenever a placeholder animation ends.JavaScript
3
Update event listener
Update your
load event listener so that it passes the onAnimationEnd callback and the first item of your PLACEHOLDERS array to animatePlaceholders.JavaScript