-1

I am trying to find a method to have a single letter change every 5 seconds. I have the random part done but cannot work out how to change it every 5 seconds. Here is what I have put together so far, I am hoping someone can tell me where I am going wrong.

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        function randomString(Length)
        {
            var text = "";
            var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            for( var i=0; i < Length; i++ )
                text += possible.charAt(Math.floor(Math.random() * possible.length));
            return text;
        }
        function ChangingRandomString(Length)
        {
            setInterval(function(){
                return randomString(Length);
            },5000);
        }
    </script>
</head>
<body>
<div id="wrap">
<p>Random Changing Letter : <script type="text/javascript">ChangingRandomString(1);</script></p>
<p>Random Static Letter : <script type="text/javascript">document.write(randomString(1));</script></p>
</div>
</body>
</html>

In the ideal world I am looking to also make the changing letter fade in and out as well for those who like a challenge :-)

Thanks in advance for any help.

Holt
  • 36,600
  • 7
  • 92
  • 139

1 Answers1

0

My suggestion:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
            function randomString(Length)
            {
                var text = "";
                var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                for( var i=0; i < Length; i++ )
                    text += possible.charAt(Math.floor(Math.random() * possible.length));
                return text;
            }
            function ChangingRandomString(Length)
            {
                setInterval(function(){
                    document.getElementById("random").innerHTML = randomString(Length);
                },5000);
            }
        </script>
    </head>
    <body>
        <div id="wrap">
        <p>Random Changing Letter : <span id="random"></span></p>
        <p>Random Static Letter : <script type="text/javascript">document.write(randomString(1));</script></p>
        </div>
    </body>
    <script>ChangingRandomString(1)</script>
</html>

Your code wasn't working because you weren't writing anywhere just calling ChangingRandomString. It simply returned something, but it wasn't being written.

This way, I used a span, that is rewritten every 5 seconds, and called the script in the end of the body tag.

For the fade thing, I really suggest you to use jQuery that facilitates that kind of things. You can also take a look here.

Community
  • 1
  • 1
Hugo Sousa
  • 1,904
  • 2
  • 15
  • 28