You are on page 1of 2

18/08/2020 How to display random lines of text from a txt file - JavaScript - The SitePoint Forums

🔥 Get 3 months access to 400+ books and courses


for just $3/m!
Get Access Now

How to display random lines of text from a txt file


force Former Community Award Winner Jan '04 #1

Is there a way in javascript to display random lines of text (ie quotes) from a txt file? I know PHP
has this ability, but the server I’m working with does not support PHP.

Level up your JavaScript skills with ‘Modern JavaScript’ - Free.


Package management, linting, transpilation, module bundling, minification, source maps, frameworks, unit testing, and
more. We wrote this book for any intermediate JavaScript developer looking to go to the next level.

Read online

awestmoreland American't Jan '04 #2

force_flow2002:

Is there a way in javascript to display random lines of text (ie quotes) from a txt file?

In short: No, because Javascript doesn’t have the ability to read external files for security
reasons.

In long: It’s possible to refer to an external Javascript which defines the quotes. Here’s one using
some quotes used on a canoeing website I created some time ago: DEMO

<html>
<head>
<title>Random Quotes</title>
<script language="JavaScript" type="text/javascript" src="quoteArra
<script language="JavaScript" type="text/javascript">
<!--
function getQuote(){

https://www.sitepoint.com/community/t/how-to-display-random-lines-of-text-from-a-txt-file/1487/2 1/3
18/08/2020 How to display random lines of text from a txt file - JavaScript - The SitePoint Forums

var thisquote=Math.floor(Math.random()*(quotes.length));
document.write(quotes[thisquote]);
}
//-->
</script>
</head>
<body>
<script language="JavaScript" type="text/javascript">
<!--
getQuote();
//-->
</script>
</body>
</html>

Contents of quoteArray.js:

var quotes=new Array();


quotes[0]="<q>Quote 1</q>";
quotes[1]="<q>Quote 2</q>";
...

You can refresh the demo site to show a new quote.


If you set the function to run onLoad however, you will get the same quote each time.

Andy

force Former Community Award Winner Jan '04 #3

Thanks, Andy

CLOSED OCT 8, '14

https://www.sitepoint.com/community/t/how-to-display-random-lines-of-text-from-a-txt-file/1487/2 2/3

You might also like