Explain Codes LogoExplain Codes Logo

Text Blinking jQuery

javascript
best-practices
functions
callbacks
Nikita BarsukovbyNikita Barsukov·Jan 15, 2025
TLDR

Get blinking text running with jQuery, we use fadeToggle() in setInterval(). Let's make your site disco! 🕺

setInterval(() => $('.blink').fadeToggle(), 500);

Add .blink class on your text elements:

<span class="blink">Blinking Text</span>

This presents your text bouncing in and out of sight at 500ms intervals. No wrestling with additional CSS required.

Building a reusable function

Let's create a reusable function that offers flexibility over the blinking action and speed of blink. This will entitle you to bonus XP in the Developer's Guild!

// A wild blinking function appears! function createBlinker(selector, interval) { var blinker = setInterval(function() { $(selector).fadeToggle(); // Now you see me... }, interval); // return { start: function() { // Now you don't! 🕴️ blinker = setInterval(function() { $(selector).fadeToggle(); }, interval); }, stop: function() { // ...and I'm back! clearInterval(blinker); } }; } // Let's put the magic to work 🔮 var myBlinker = createBlinker('.blink', 1000); myBlinker.start(); // Kick-off the lightshow! myBlinker.stop(); // Call it a day.

This function is a beacon of best practice for clean, maintainable code.

While turning on the rushlight of text-blinking feature, you should pay heed to:

  • User experience: Too much blinking could trigger distraction. Remember, with great power comes great responsibility! 🦸
  • Performance: Incorrect use of setInterval() could lead to performance drops. Let's keep our users' hardware healthy!
  • Clean-up: Always provide an exit door to clear intervals, preventing any memory leaks or dreadful "Out of memory" errors.

Embracing modern developments

If you're racing with modern browsers, you can showcase your finesse with CSS3 animations:

@blink { 50% { opacity: 0; } } .blink { animation: blink 1s step-start 0s infinite; }

Just marry this elegant CSS with your plain HTML:

<span class="blink">Blinking Text</span>

Keeping things tidy and light

In this world of complexities, sometimes simple is better. If you believe so, CSS transitions can cut your jQuery reliance:

.blink { animation: blink 1s infinite alternate; } @keyframes blink { from { opacity: 1; } to { opacity: 0; } }

This approach has the advantage of being resource-light and maintaining a clean, smooth effect.