If you prefer an instant transition between show and hide instead of a gradual one (like a blinking text cursor), you can achieve that effect with the following code snippet:
/* Make sure to use prefixes with @keyframes and animation for browser support */
@keyframes blinker {
from { visibility: visible }
to { visibility: hidden }
/* Another approach:
0% { visibility: visible; }
50% { visibility: hidden; }
100% { visibility: visible; }
if `alternate` is not desired */
}
.cursor {
animation: blinker steps(1) 500ms infinite alternate;
}
With this code, every 1s
, the .cursor
will toggle between being visible
and hidden
.
In cases where CSS animation is not supported (such as some Safari versions), you can rely on a simple JavaScript interval as a fallback option:
(function(){
var show = 'visible'; // variable to track state toggled by interval
var time = 500; // time in milliseconds between each interval
setInterval(function() {
// Toggle visibility state on each interval
show = (show === 'hidden') ? 'visible' : 'hidden';
// Select all cursor elements
var cursors = document.getElementsByClassName('cursor');
// Loop through cursor elements and update their visibility based on current state
for (var i = 0; i < cursors.length; i++) {
cursors[i].style.visibility = show;
}
}, time);
})()
This straightforward JavaScript solution may actually perform faster than CSS animations in certain scenarios. It's important to note that excessive DOM calls are what typically slow down JS animations (e.g. JQuery's $.animate()).
Additionally, a benefit of using this JavaScript method is that any new .cursor
elements added later will still animate simultaneously with existing ones since they share the same state - something not achievable with CSS alone.