Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make a word spell out in the page delayed with javascript?

Strange question I know. I am trying to get a word to load letter by letter on a page with a small delay. Yes this is what I think about sometimes when I am coding at work. I have tried numerous methods with absolutely no success. The best I got was an alert box with the following code but I want to do it with the html on the page. Is this even 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 am assuming there has to be some type of set time out with a hide show and a div to load it into?

like image 725
Martin Brody Avatar asked Dec 02 '22 01:12

Martin Brody


2 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 the HTML:

  <div id="word"></div>
like image 200
Vincent Ramdhanie Avatar answered Jan 25 '23 10:01

Vincent Ramdhanie


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

<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);
}
like image 32
Adam Rackis Avatar answered Jan 25 '23 09:01

Adam Rackis