/    Sign up×
Community /Pin to ProfileBookmark

Randomly placed text

Hi,

I have been asked to construct a page which will place text-only adverts into ten different “boxes.”

I think the best way to do this would be to define ten <DIV>’sthen use a script to place the text from an array onLoad. However, I am stumped as to how to randomly select text.

Any suggestions would be gratefully received.

Thanks in advance.

Pylo

to post a comment
JavaScript

5 Comments(s)

Copy linkTweet thisAlerts:
@fredmvApr 12.2004 — Welcome to the forums.

If you merely want to know how to select a random element out of an array, check the example below.&lt;script type="text/javascript"&gt;
//&lt;![CDATA[
var foo = ['hello', 'world', 'foo', 'bar'];
alert(foo[Math.floor(Math.random()*foo.length)]);
//]]&gt;
&lt;/script&gt;
Copy linkTweet thisAlerts:
@VladdyApr 12.2004 — <i>
</i>Array.prototype.swap = function(index1,index2)
{ var temp = this[index1];
this[index1] = this[index2];
this[index2] = temp;
return;
}

Array.prototype.shuffle = function()
{ for(var i=0; i&lt;this.length; i++)
{ ind1 = Math.floor(Math.random()*this.length);
ind2 = Math.floor(Math.random()*this.length);
this.swap(ind1,ind2);
}
return;
}
Copy linkTweet thisAlerts:
@PyloauthorApr 12.2004 — Thanks guys!

Definitely something to work on there so thanks!

However, I want to have an array of ten blocks of text to be placed randomly in ten DIV's with no repeats. How can I achieve this?

TIA

Pylo
Copy linkTweet thisAlerts:
@VladdyApr 12.2004 — Use the shuffle method I posted on your array before placing the text into elements.
Copy linkTweet thisAlerts:
@steelersfan88Apr 12.2004 — and if you didn't get it, you will need both prototypes in your code, and simply shuffle by:myArray.shuffle()vlad's script should work in what you need, then simply loop to place each in a div, kinda like:[code=php]for(var i=0;i<myArray.length;i++) {
// or ".".innerHTML = "..."
document.getElementById('div'+ i).firstChild.nodeValue = myArray[i]
}[/code]
×

Success!

Help @Pylo spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...