Typing Text Effect Shortcode
Adds a [wpide_typing words="faster|safer|simpler"] shortcode that types and deletes each word in turn, for lively hero headlines like "Make your site faster".
Opens WPIDE on
Code
add_action( 'wp_enqueue_scripts', function () {
wp_register_style( 'wpide-typing', false, array(), '1.0' );
wp_add_inline_style( 'wpide-typing', '.wpide-typing__text::after{content:"";display:inline-block;width:2px;height:1em;margin-left:2px;vertical-align:-.1em;background:currentColor;animation:wpide-caret 1s steps(1) infinite;}@keyframes wpide-caret{50%{opacity:0;}}@media (prefers-reduced-motion:reduce){.wpide-typing__text::after{display:none;}}.wpide-typing .screen-reader-text{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;}' );
wp_register_script( 'wpide-typing', false, array(), '1.0', true );
wp_add_inline_script( 'wpide-typing', <<<'JS'
(function () {
var reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
document.querySelectorAll('.wpide-typing').forEach(function (el) {
var words = JSON.parse(el.getAttribute('data-words') || '[]');
var out = el.querySelector('.wpide-typing__text');
if (!words.length || !out) { return; }
if (reduce) { out.textContent = words[0]; return; }
var w = 0, c = 0, deleting = false;
function tick() {
var word = words[w];
c += deleting ? -1 : 1;
out.textContent = word.slice(0, c);
var delay = deleting ? 45 : 90;
if (!deleting && c === word.length) { deleting = true; delay = 1600; }
else if (deleting && c === 0) { deleting = false; w = (w + 1) % words.length; delay = 350; }
setTimeout(tick, delay);
}
tick();
});
})();
JS
);
} );
add_shortcode( 'wpide_typing', function ( $atts ) {
$atts = shortcode_atts( array( 'words' => 'faster|safer|simpler' ), $atts, 'wpide_typing' );
$words = array_values( array_filter( array_map( 'trim', explode( '|', wp_strip_all_tags( $atts['words'] ) ) ) ) );
if ( ! $words ) {
return '';
}
wp_enqueue_style( 'wpide-typing' );
wp_enqueue_script( 'wpide-typing' );
return sprintf(
'<span class="wpide-typing" data-words="%1$s"><span class="screen-reader-text">%2$s</span><span class="wpide-typing__text" aria-hidden="true">%3$s</span></span>',
esc_attr( wp_json_encode( $words ) ),
esc_html( implode( ', ', $words ) ),
esc_html( $words[0] )
);
} );
Notes
Separate words with a vertical bar. Screen readers read the full list once, and visitors who prefer reduced motion see the first word without animation.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.