^ Click Here

Saturday, September 1, 2012

jQuery : Showing the text in typing (typewriter) effect

I was trying for it and came out with an idea so that we can show the text and messages as someone is typing it (of course that's an illusion like much of other things).

So here it goes. You have a text message and you want to show it with the effect, first of all we need to break the sentence for each single letter or alphabet and then would need to put it one after another with certain time-difference. the logic seems simple.

So here is the primary function for it :-

function demoTypeWriting(){
  var text = "Our whole theory of education is based on the absurd notion that we must learn to swim on land before tackling the water."
  var textArray = text.split("");
  $('div#resultDiv').append('<div id="typeText"></div>');
  timer = setInterval( function(){writeText(textArray)}, 500 ); 
}

Once it's done, I would provide for the function which will actually execute the task of typing the text :-

function writeText(textArray){
    if(textArray.length > 0){
    console.log(textArray[0]);
    $('div#newText').focus().append(textArray[0]);
    textArray.splice(0,1);
    }
    else{
        clearInterval(timer);
    }
}

So as you can see I am doing nothing great I am putting first element into the designated div and since it's already has been put, I am removing it from the array, So that next element can be put. Finally when array is empty I am stopping the timer. 

Try it here :-

Your Text:
Time Difference :

Result : -

No comments:

Post a Comment