Javascript to show text for a specified duration (in milliseconds) | XM Community
Skip to main content
I am trying to use Javascript to show text for a specified duration (in milliseconds). I want the question to remain, but the text hidden after the time elapses. However, the code is not working. Can someone help please?



//flash single text for specified duration

var text = "Write text to be displayed here";

var time = 1500; //time in milliseconds

var c = this.questionContainer;

var tc = QBuilder('span',{},text);

$(tc).setStyle({color:'red',fontSize:'24pt'}); //optional to change text style

var ic = QBuilder('div',{},[tc]);

$(c).appendChild(ic);

(function(){

$(ic).clonePosition(tc); //comment this line out to remove the white space left after the

text is hidden

$(tc).hide();

}).delay(time/1000);
Instead of all the extra variables creating the message, just write it in the rich text editor, style it how you want, switch to the code view and add an ID to the element or wrap it in a div with the id

```

<div id="msg">Your message</div>

```



and then in the JS, just use the native setTImeout



```

setTimeout(function(){

$("#msg").hide();

}, 5000);

```



see docs



This all assumes it's a question the user sees within the 1st 5 seconds of the page load. If you want to delay until the question comes into view you either need to use the modern IntersectionObserver (new browsers) or do some polling and checking for visibility on scroll. This post will get you part of the way there.

Leave a Reply