Alternatively if you do not want a gradual transition between show and hide (e.g. a blinking text cursor) you could use something like:
/* Also use prefixes with @keyframes and animation to support current browsers */
@keyframes blinker {
from { visibility: visible }
to { visibility: hidden }
/* Alternatively you can do this:
0% { visibility: visible; }
50% { visibility: hidden; }
100% { visibility: visible; }
if you don't want to use `alternate` */
}
.cursor {
animation: blinker steps(1) 500ms infinite alternate;
}
Every 1s
.cursor
will go from visible
to hidden
.
If CSS animation is not supported (e.g. in some versions of Safari) you can fallback to this simple JS interval:
(function(){
var show = 'visible'; // state var toggled by interval
var time = 500; // milliseconds between each interval
setInterval(function() {
// Toggle our visible state on each interval
show = (show === 'hidden') ? 'visible' : 'hidden';
// Get the cursor elements
var cursors = document.getElementsByClassName('cursor');
// We could do this outside the interval callback,
// but then it wouldn't be kept in sync with the DOM
// Loop through the cursor elements and update them to the current state
for (var i = 0; i < cursors.length; i++) {
cursors[i].style.visibility = show;
}
}, time);
})()
This simple JavaScript is actually very fast and in many cases may even be a better default than the CSS. It's worth noting that it is lots of DOM calls that make JS animations slow (e.g. JQuery's $.animate()).
It also has the second advantage that if you add .cursor
elements later, they will still animate at exactly the same time as other .cursor
s since the state is shared, this is impossible with CSS as far as I am aware.