Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 11 of 11
  1. #1
    New to the CF scene
    Join Date
    Sep 2010
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Implement setInterval() with "random array picker"

    Hi. I'm working on a script that picks out a random entry in an array every 10seconds and show it to the user (using document.write). So far I've got the "Randomizer" to work like this:

    Code:
    function random(){
    	var nummer = Math.floor(Math.random()* tekst.length);
    	return nummer;
    }
    
    var tekst = new Array("Different", "Values");
    and showing it like this:

    Code:
    document.write(tekst[random()]);
    Now, I've tried my best to implement setInterval() to give me a new random number every 10seconds, but so far without any luck...

    I appreciate all help!

    Thx in advance.

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,303
    Thanks
    203
    Thanked 2,562 Times in 2,540 Posts
    Use setTimeout()

    document.write statements must be run before the page finishes loading. Any document.write statement that runs after the page finishes loading will create a new page and overwrite all of the content of the current page. So document.write is at best really only useful to write the original content of your page. It cannot be used to update the content of your page after that page has loaded.


    All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.

  • #3
    New to the CF scene
    Join Date
    Sep 2010
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Philip M View Post
    Use setTimeout()

    document.write statements must be run before the page finishes loading. Any document.write statement that runs after the page finishes loading will create a new page and overwrite all of the content of the current page. So document.write is at best really only useful to write the original content of your page. It cannot be used to update the content of your page after that page has loaded.
    Okay. How do I show the result then?

  • #4
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,303
    Thanks
    203
    Thanked 2,562 Times in 2,540 Posts
    Quote Originally Posted by The Covenant View Post
    Okay. How do I show the result then?
    Use a <span>, e.g. <span id = "yourSpan">Something here</span>

    Then in a script

    document.getElementById("yourSpan").innerHTML = result;

    There are lots of good examples of this sort of thing posted on this forum.
    Have a look at http://codingforums.com/javascript-programming/203899-cannot-add-links-changing-rotating-text-lines.html
    Post #6.

    Be aware that a random number generator such as you are attempting may well generate the same random number twice (or even three times) in succession, especially if the number of numbers is small. So the best approach is to shuffle the text array elements at the outset, and then display them in order 1,2,3,4 etc. This way you get no duplication.


    Here is an example:

    Code:
    <span id = "q1"></span><br>
    
    <script type = "text/javascript">
    
    shuffle = function(v){
    for(var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
    return v;
    }
    
    var quotations = new Array();
    quotations[0]= "germaine arnold"
    quotations[1]= "endearing moral"
    quotations[2]= "analog reminder"
    quotations[3]= "regained normal"
    quotations[4]= "renaming ordeal"
    quotations[5]= "nominal regrade"
    quotations[6]= "arraigned lemon"
    quotations[7]= "ringleader moan"
    quotations[8]= "mineral groaned"
    var shf = shuffle(quotations);
    
    var index  = 0;
    function show() {
    document.getElementById("q1").innerHTML = quotations[index];
    index ++;
    if (index > 8) {index = 0} // start again with same sequence of quotations
    //if (index > 8) {index = 0; shuffle(quotations)}  // re-shuffle quotations into a new sequence and start again
    setTimeout("show()",10000);  // 10 seconds delay
    }
    
    show();
    
    </script>
    Last edited by Philip M; 09-04-2010 at 11:18 AM.

  • Users who have thanked Philip M for this post:

    Sciliano (09-04-2010)

  • #5
    New to the CF scene
    Join Date
    Sep 2010
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Philip M View Post
    Use a <span>, e.g. <span id = "yourSpan">Something here</span>

    Then in a script

    document.getElementById("yourSpan").innerHTML = result;

    There are lots of good examples of this sort of thing posted on this forum.
    Have a look at http://www.codingforums.com/showthread.php?t=203899
    Post #6.
    Well. I looked at the link you gave me, but it didn't help me that much... I'm very new in this JavaScript world.

    But, do I write it like this?

    Code:
    document.getElementById("id of my <p>").innerHTML = tekst[random()];

  • #6
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,303
    Thanks
    203
    Thanked 2,562 Times in 2,540 Posts
    Quote Originally Posted by The Covenant View Post
    Well. I looked at the link you gave me, but it didn't help me that much... I'm very new in this JavaScript world.

    But, do I write it like this?

    Code:
    document.getElementById("id of my <p>").innerHTML = tekst[random()];
    Oh, sorry I spoke! If you cannot learn from the examples given you would perhaps be best to give up JavaScript and take up underwater motorcycling instead.

    var nummer = Math.floor(Math.random()* tekst.length);
    document.getElementById("id of my <p>").innerHTML = tekst[nummer];

  • #7
    New to the CF scene
    Join Date
    Sep 2010
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Philip M View Post
    Oh, sorry I spoke! If you cannot learn from the examples given you would perhaps be best to give up JavaScript and take up underwater motorcycling instead.

    var nummer = Math.floor(Math.random()* tekst.length);
    document.getElementById("id of my <p>").innerHTML = tekst[nummer];
    Hehe... I'm trying here...! But nothing happens when I write it like this...

  • #8
    Regular Coder
    Join Date
    Jan 2006
    Posts
    568
    Thanks
    6
    Thanked 84 Times in 84 Posts
    When does the script run? If it's called in the head or above the <p>, the <p> won't exist at the time of execution.

    If you look in the error console you might find something like
    document.getElementById("id of p") is null or not an object

  • #9
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,303
    Thanks
    203
    Thanked 2,562 Times in 2,540 Posts
    Quote Originally Posted by The Covenant View Post
    Hehe... I'm trying here...! But nothing happens when I write it like this...
    document.getElementById("id of my <p>").innerHTML = tekst[nummer];

    The id must of course be the actual id. And the <p> must exist at the time the script is executed.

    Why not simply use the examples you were provided with?

  • #10
    New to the CF scene
    Join Date
    Sep 2010
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Philip M View Post
    document.getElementById("id of my <p>").innerHTML = tekst[nummer];

    The id must of course be the actual id. And the <p> must exist at the time the script is executed.

    Why not simply use the examples you were provided with?
    but of course! still didn't work... but i guess I'll just have to try until I get it right...

  • #11
    Regular Coder
    Join Date
    Nov 2009
    Posts
    247
    Thanks
    4
    Thanked 22 Times in 22 Posts
    Covenant:

    Using my code from here:
    cannot add links to changing/rotating text lines which was cited by Philip M, I inserted Philip M's array randomization code from here:
    Random fact selection

    Just copy the entire post, save it as an .html document, then open that document in your browser.

    What more do you expect someone to do? Make an effort to help yourself.

    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>None</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript">	
    	
    	var rotate = "";
    	var nMessage = 0;	
    	
    	function rotateMessage(messageContainer,rotateDelay,messages){
    
    		messageContainer.firstChild.data = messages[nMessage];	
    		nMessage = nMessage == messages.length-1 ? 0 : nMessage + 1;			
    		rotate = setTimeout
    			(
    			 function()
    				{
    				 rotateMessage(messageContainer,rotateDelay,messages)
    				}
    			 , rotateDelay * 1000 
    			);	
    	}
    
    	function randOrd(){
    		
    		return (Math.round(Math.random())-0.5);
    	}
    
    	function init(){		
    
    		var rotateDelay = 3;  // 3 seconds;
    		var randomize = true; // or false;
    
    		var messages = [];		
    		var nDiv = document.getElementsByTagName('div');
    		for (i=0; i<nDiv.length; i++)
    			{
    			 if (nDiv[i].className == "message_display")
    				{
    				 var messageContainer = nDiv[i];
    				 var nItems = nDiv[i].getElementsByTagName('ul')[0].getElementsByTagName('li');
    				 for (n=0; n<nItems.length; n++)
    					{
    					 messages[messages.length] = nItems[n].firstChild.data;
    					}
    				}
    			}
    		while(messageContainer.lastChild)
    			{
    			 messageContainer.removeChild(messageContainer.lastChild);
    			}
    		if (randomize)
    			{			 
    			 messages.sort(randOrd);
    			}
    		messageContainer.appendChild(document.createTextNode(' '));
    		messageContainer.onmouseover = function()
    			{
    			 this.style.cursor = "wait";
    			 clearTimeout(rotate);
    			 this.onmouseout = function()
    				{
    				 this.style.cursor = "default";
    				 rotate = setTimeout
    					(
    					 function()
    						{
    						 rotateMessage(messageContainer,rotateDelay,messages)
    						}
    					 , rotateDelay * 1000 * .25
    					);
    				}
    			}	
    		rotateMessage(messageContainer,rotateDelay,messages)
    	}
    
    	navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);	
    
    </script>
    <style type="text/css">
    
    	 body {background-color: #fffacd; margin-top: 60px;}
    	.message_display {width: 500px; border: 1px solid black; text-align: center; 
    	            	  font-family: tahoma; font-size: 12pt; background-color: #eee8aa;
    		    	  font-weight: bold; padding: 3px; margin: auto; cursor: default;}
    	.message_display ul {margin: 0px;}
    
    </style>
    </head>
    	<body>
    		
    		<div class="message_display">
    			<ul>
    				<li>This is the first message</li>
    				<li>This is the second message</li>
    				<li>This is the third message</li>
    				<li>This is the fourth message</li>
    				<li>This is the fifth message</li>
    			</ul>
    		</div>		
    
    	</body>
    </html>
    Last edited by Sciliano; 09-04-2010 at 01:10 PM.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •