How to create a simple Ticker in HTML using JavaScript

Introduction

In this post we will see how to create a simple Ticker in HTML using JavaScript

Description

We can create a simple Ticker in HTML using JavaScript that will display a string character by character. It will simulate like being typed using keyboard. We will use JavaScript setInterval() function to delay the display of characters

<html>
<head>
     <title>MyTicker</title>
     <style type="text/css">
          .MyStyle
          {
               width:500px;height:150px;background-color:Purple;color:White;
          }
     </style>
</head>
<body>
     <div id="MyTicker"
          style="width:500px;height:150px;background-color:Purple;color:White;">
     </div>
     <script type="text/javascript">
          var text = "We can create a simple Ticker in HTML using JavaScript "+
                     "that will display a string character by character. It will simulate "+
                     "like being typed using keyboard";
          var intervalId = null;
          var obj = document.getElementById("MyTicker");
          var tickerText = "";
          var i = 0;
          intervalId= setInterval(tick, 100);

          function tick() {
               tickerText += text.charAt(i);
               obj.innerHTML = tickerText+"_";
               i++;
               if (i == text.length) {
                    // stops timer
                    clearInterval(intervalId);
                    // removes last underscore
                    tickerText = tickerText.substring(0, text.length);
                    obj.innerHTML = tickerText;
               }
          }
     </script>
</body>
</html>

Here first we have added a DIV to display the ticker. Then in the script tag we have used setInterval function to run a function named tick() every 100 milliseconds. This function takes one character at a time from the sample text at the top and append to a string variable “tickerText”. This text is then set to innerHTML of the DIV and underscore is appended to it.

clearInterval() function is used to stop execution of the tick() function when all the characters in the sample text has been displayed. It takes interval id of returned by the setInterval function as a parameter. Interval id is just an identifier to identify that block of code. In the last character (underscore) is removed from the tickerText

3 thoughts on “How to create a simple Ticker in HTML using JavaScript

  1. Anoop

    above code very useful for me I used your code but I need one more thin that I want to break line and continue with next line

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *