Search code examples
csscss-transitionscss-animationscss-content

Dynamically changing content of a SPAN


How can I dynamically change the content of a <span> tag in an infinite loop.

I have tried using the below method. Is it possible to do this with pure CSS animations? If it is not possible with pure CSS, please suggest an alternate method.

HTML:

<p>Lorem ipsum <span></span> sit amet.</p>

CSS:

span {
    content: '';
    animation: flip 2s infinite;
}
@keyframes flip {
    10% {
        content: 'Example no1';
    }
    40% {
        content: '';
    }
    80% {
        content: 'Example no2';
    }
    100% {
        content: '';
    }
}

Demo Fiddle


Solution

  • Changing the content of a span dynamically using the content property is not possible. It was originally designed to be used only with pseudo-elements (like :before or :after).

    However, this can be achieved with just HTML and Javascript like shown below:

    var i = 0; // The counter variable
    var arrayLength = 5; // The max length of the data array 
    var dataArray = ['Example 1', 'Example 2', 'Example 3', 'Example 4', 'Example 5']; // The actual data which have to be shown in a loop
    
    function changeval() {
        if (i == arrayLength) i = 0; // If counter reaches max length, reset it
        document.getElementById('dataSpan').innerHTML = dataArray[i]; // Set the value to the span
        i++; // Increment counter
    }
    
    setInterval(changeval, 500); // Call the function to change value at defined intervals
    <!-- Just add an ID to your span to which the content must be set -->
    <p>Lorem ipsum <span id='dataSpan'></span> sit amet.</p>


    Though CSS isn't the best for your case, the below can be achieved using a few CSS tricks/hacks if the no. of items in your array is small/finite.

    body, html{
        font-size: 16px;
    }
    #dataSpan {
        height: 1.25em;
        overflow: hidden;
        display: inline-block;
        vertical-align: top;
        padding: 0px;
        line-height: 1.25em;
        top:0;
    }
    #dataSpan span {
        position: relative;
        -webkit-animation: changeContent 5s steps(4) infinite;
        -moz-animation: changeContent 5s steps(4) infinite;
        animation: changeContent 5s steps(4) infinite;
    }
    @-webkit-keyframes changeContent {
        from{top:0;}
        to {top:-5em;}
    }
    @-moz-keyframes changeContent {
        from{top:0;}
        to {top:-5em;}
    }
    @keyframes changeContent {
        from{top:0;}
        to {top:-5em;}
    }
    <p>Lorem ipsum <span id="dataSpan">
            <span>Example 1<br>Example 2<br>Example 3<br>Example 4<br>Example 5</span>
    </span> sit amet.</p>