...

View Full Version : adapting random script to fire from link, not onload



ctoz
09-06-2008, 07:12 PM
Cut'n'paster here, having trouble with some basics.

The script in question comes from Javascript Kit (http://javascriptkit.com/script/script2/randomcontent.shtml), given in full below.

It delivers a random div; it's set up to deliver when the page is loaded, or refreshed. It's initialised with a script call at the bottom of the html page.

I want the script to deliver from an onclick event.

What I don't understand is whether in this situation it needs to be initialised; and whether the onclick call would be, in the script below, 'showone()' or 'showone:function()' . Or maybe it's not that simple?



Here's the script in full:

if (document.getElementById)
document.documentElement.className = 'jsclass';

var randomcontentdisplay={
divholders:new Object(),
masterclass: "randomcontent",

init:function(){
if (!document.getElementById)
return
var alldivs=document.getElementsByTagName("div")
var randomcontentsearch=new RegExp(this.masterclass+"\\s+(group\\d+)", "i") //check for CSS class="randomcontent groupX" (x=integer)
for (var i=0; i<alldivs.length; i++){
if (randomcontentsearch.test(alldivs[i].className)){
if (typeof this.divholders[RegExp.$1]=="undefined") //if array to hold this group of divs doesn't exist yet
this.divholders[RegExp.$1]=new Array() //create array first
this.divholders[RegExp.$1].push(alldivs[i]) //add this div to the array
}
}
this.showone()
},
/* :confused: */

showone:function(){
for (group in this.divholders){ //loop thru each array within object
var chosenOne=Math.floor(Math.random()*this.divholders[group].length) //randomly pick one entry from array
this.divholders[group][chosenOne].style.display="block" //display content corresponding to the chosen entry
}
}
}

and the initialising call:

<script type="text/javascript">
randomcontentdisplay.init()
</script>

jeremysnyder
09-09-2008, 07:49 PM
to answer your question, you want to move "randomcontentdisplay.init()" into the onclick event... like the following:


onclick="randomcontentdisplay.init();"

The init() function calls the showone() method for you when it is finished.

Jeremy A. Snyder
http://snydersoft.com

ctoz
09-10-2008, 07:57 AM
Many thanks... Can you handle a related query?

Suppose I want to use this random function several times (nine actually), calling, say, one of four divs at random from onclick 1, one of five others from onclick 2, etc.

I could group the divs by giving them different classnames, but how to avoid repeating the whole script using the new classnames? It lloks like it would need a new variable?

Alternatively, if one were to use 'slice' method, it'd need an array in the first place, and then where would one situate the slices?

IDon't mind having a stab at the code myself, given some pointers.

Cheers



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum