0

I have rendered data into EJS and now using a while loop I want to cycle through that data and display it on a single line. For example let's say the data is an array of objects with name attributes. I have the names ['Bob','Chris','Sarah']. After I have sent the data over to EJS I want Bob to appear, and then after some time Bob disappears and then Chris appears and then Sarah appears.

As of right now my code outputs them all at once over multiple lines, instead of one at a time on a single line as I desire.

<body>
    <% var current = 0; %>
    <% while (current < 2){ %>
        <h1> Hey <%= person[current].name %>, how are you doing? </h1>
    <%    current += 1;
    };%>
</body>

The output should be on a single line: Hey CURRENT NAME, how are you doing? Then the current name should just keep changing.

Instead the code outputs three lines, one for each name. Does anybody know how to fix this? Thanks.

Rajan
  • 73
  • 1
  • 8

1 Answers1

0

I think you are confusing template processing (which produces static output) with dynamic updating of a DOM element. The latter is more of a problem for a front-end framework (although just what you have provided is simple enough in vanilla JS).

I would look into just creating a template with a placeholder for the name and then use a timer to update the text inside:

setInterval(3000, function(){
    var span = document.getElementById('name-span');
    if ('textContent' in span) {
        span.textContent = person[current].name;
    } else {
        span.innerText = person[current].name;
    }
    current = (current + 1) % person.length;
}

Of course you need to figure out a better way to access person and current instead of using globals.

DDupont
  • 441
  • 2
  • 11