Show different text on blink using Javascript?

1.6k views Asked by At

I want to show changing text in few second in only one div.

var blink_speed = 1000; // every 1000 == 1 second, adjust to suit
var t = setInterval(function () {
    var ele = document.getElementById('myBlinkingDiv');
     ele.style.visibility = (ele.style.visibility == 'hidden' ? '' : 'hidden');
}, blink_speed);
        <div id="myBlinkingDiv">Blink 0</div>
     <div id="myBlinkingDiv1">Blink 1</div>
     <div id="myBlinkingDiv2">Blink 2</div>
     <div id="myBlinkingDiv3">Blink 3</div>
     <div id="myBlinkingDiv4">Blink 4</div>
     <div id="myBlinkingDiv5">Blink 5</div>
     <div id="myBlinkingDiv6">Blink 6</div>
     <div id="myBlinkingDiv7">Blink 7</div>
     <div id="myBlinkingDiv8">Blink 8</div>
     <div id="myBlinkingDiv9">Blink 9</div>
     <div id="myBlinkingDiv10">Blink 10</div>

Mine is not working. I'm unable to run array here.

3

There are 3 answers

1
GeekAb On BEST ANSWER

You actually don't need multiple div's.

Better create an array of all text you want to show and use javascript to change that.

Check my example : http://jsbin.com/napelobura/edit?html,js,output

<div id="text"></text>


var blink_speed = 1000;
var wordArray = ['One', 'Two', 'Three'];
var count=0;
var t = setInterval(function () {
    var ele = document.getElementById('text');

    ele.innerHTML = wordArray[count++];

   if(count===wordArray.length)
     count=0;

}, blink_speed);

What I am trying to do is, I am changing content of div every few second set by blink_speed and checking count for length of array.

0
baao On

For what you have posted, the following will do the trick:

var blink_speed = 1000; // every 1000 == 1 second, adjust to suit
var ele = document.getElementById('myBlinkingDiv');
var t = setInterval(function () {
     var number = parseInt(ele.innerHTML.replace(/\D/g, ""));
     if (number > 10) number = -1;
     ele.innerHTML = "Blink " + ++number;
}, blink_speed);
<div id="myBlinkingDiv">Blink 0</div>

Of course you can adjust this to change the text to something entirely different...

0
Roshni Bokade On
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
   <script>
       function start() {
           var i = 0;
           setInterval(function () {
               document.getElementById('myBlinkingDiv').innerHTML="Blink " + i;
               i = i + 1;        
           },1000);
       }
   </script>

</head>
<body>
    <input type="button" onclick="start();" value="Start"/>
  <div id="myBlinkingDiv"></div>
</body>
</html>