SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    John 8:24 JREAM's Avatar
    Join Date
    Sep 2007
    Location
    Florida
    Posts
    1,508
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Writing Function to Document

    I got this from a site and was trying to edit it my own to figure it out, i dont understand the (rnum,rnum+1) what that does "\
    Code JavaScript:
    function randomString(){
        var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        var strlen = 8;
     
        for (var i = 0; i < strlen; i++); {
            var rnum = Math.floor(Math.random() * chars.length);
            randomString += chars.substring(rnum,rnum+1);
        }
        return randomString;
    }

    1. Im having trouble writing this to the document, how do you do a document.write(function());? is that possible, or do I need to do a getElementbyID for something like this?

    2. Does is matter if i have vars for a function outside of the function?

  2. #2
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You are redefining the function randomString in midstream.

  3. #3
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    A script in the head would do it, using innerHTML or, as in this example,
    document objects to write to the page on load:
    <script type="text/javascript">
    Code:
    (function randomString(len){
    	window.onload= function(){
    		var pa= document.body;
    		var sib= pa.firstChild;
    		var el= document.createElement('h1');
    		// or select an element by id or obj reference
    
    		el.style.cssText= 'position:relative; display:inline;background:black none;color:white;border:1px dashed red';
    		// the css would be better in a stylesheet
    
    		el.appendChild(document.createTextNode(window.randomKey));
    		pa.insertBefore(el,sib);
    	}
    	len= len || 8;
    	var A= [];
    	while(A.length< len){
    		var n= 47;
    		while(n<122){
    			var tem= String.fromCharCode(++n);
    			if(/[a-z0-9]/i.test(tem)) A.push(tem);
    		}
    		A.sort(function(){return .5-Math.random()});
    	}
    	window.randomKey= A.splice(0,len).join('');
    })()
    </script>


Bookmarks

Posting Permissions

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