Is it possible to write a word on a page with a delay using javascript?

A strange question that I know. I am trying to get the word to load a letter by letter on a page with a slight delay. Yes, this is what I sometimes think about when I code at work. I tried many methods, completely unsuccessfully. The best I got is a warning window with the following code, but I want to do this using html on the page. Is it possible?

<script type="text/javascript"> var foo = "foo bar"; foo = foo.length ; for(i= 1; i<=foo; i++){ var hello = "FOO BAR"; hello = hello.substring(0, i); alert(hello); } </script> 

I guess there must be some type of timeout with showing hide and div in order to load it?

+4
source share
4 answers

You can try something like this:

  var word = "Hello World"; function nextChar(i){ $("#word").text("The Word is: [" + i + "]" + word.substring(0, i)); if(i < word.length){ setTimeout("nextChar(" + (i + 1) + ")", 1000); } } $(document).ready(function(){ nextChar(0); }); 

And HTML:

  <div id="word"></div> 
+11
source

Let's say you want to load the "foo bar" into this div, one character at a time, with a delay of 1 second.

 <div id="destination" /> $(function () { loadWord("foo bar", 0); }); function loadWord(word, index) { if (index == word.length) return; $("#destination").text($("#destination").text() + word[index]); setTimeout(function() { loadWord(word, index + 1); }, 1000); } 
+6
source

A bit more jQuery-ish answer

The main differences from others (besides jQuery and in general):
1) animation
2) DOM-manipulation only at boot 3) the specified width (will not push other things)

+1
source

Here is the fancier version that makes the jQuery plugin to add text to any object, and it disappears in each subsequent letter. You can see how it works here: http://jsfiddle.net/jfriend00/yMJsc/ .

You call it this way:

 $(".myClass").revealText("The quick brown fox jumped over the fence.", 500); 

And here is the code for implementing the jQuery plugin.

 $.fn.revealText = function(text, duration) { duration = duration || 250; for (var i = 0; i < this.length; i++) { showNextChar(this[i], 0); } function showNextChar(item, len) { var base = text.substr(0, len); var nextChar = text[len]; // don't fade in a space since it wouldn't be visible var aheadChar = text[len + 1]; if (aheadChar == " ") { nextChar += aheadChar; ++len; } item.innerHTML = base + '<span class="fadeLetter" style="display: none;">' + nextChar + '</span>'; ++len; $(".fadeLetter", item).fadeIn(duration, function() { if (len < text.length) { showNextChar(item, len); } else { item.innerHTML = text; } }); } return(this); } 
+1
source

Source: https://habr.com/ru/post/1384436/


All Articles