Looking to figure out how to use the typewriter function to print paragraphs that contain new lines/breaks | XM Community
Skip to main content

Hello all, 

I’m trying to figure out how to use a typewriter function in JavaScript in order to print a text that appears when participants click into the question. 

 

My goal is to gradually print 4 paragraphs on the screen using the typewriter function. So far, I have managed to figure out how to type the first paragraph, but I’m having trouble figuring out how to create a new line. I have tried embedding \n and \\n into the quotation marks of the txt variable, but that has not been successful in creating a new line. Based on my code below, does anyone know what I’m missing or what I could try differently to get two consecutive new lines in my paragraph?

 

Here is what I have so far:

HTML:

<html>
<body>


<p id="demo"></p>
<p> &nbsp </p>

<script>
var i = 0;
var txt = '';


function typeWriter() {
  if (i < txt.length) {
    document.getElementById("demo").innerHTML += txt.charAt(i);
    i++;
    setTimeout(typeWriter, speed);
  }
 
}
typeWriter()
</script>

</body>
</html>

 

JavaScript:

Qualtrics.SurveyEngine.addOnReady(function()
{


function typeWriter() {
      if (i < txt.length) {
         document.getElementById("demo").innerHTML += txt.charAt(i);
         i++;
         setTimeout(typeWriter, speed);
      }
    
  }

var i = 0;

   
  var speed = 10;

var txt = "In general, the impact of social media on society is undeniably positive, providing numerous benefits that enhance communication, connectivity, and the exchange of ideas. Social media platforms serve as powerful tools for fostering global connections, empathy, and enabling individuals to communicate and share experiences across vast distances."


typeWriter();


});

@averykirkpatrick Put this style after <html> then you can use \n for line break as normal

<style type="text/css">#demo {
white-space: pre-wrap;
}
</style>

Hope this helps


Leave a Reply