...

View Full Version : How to call an array thats in a different file



TheDave
12-15-2010, 05:15 PM
Hi Guys,

I dont use JS much, I did take it in school years ago but cant remember much of it, what Im trying to do is quite simple, just a random quote gen but I want it to get the quots from a separate file as the quotes will appear on every page so I dont want to have to edit each page every time a new one needs to be added.

I just found a simple quote generator online that I want to modify to call the array from a different file, the gen looks like this:


var Quotation=new Array() // do not change this!

Quotation[0] = "Time is of the essence! Comb your hair.";
Quotation[1] = "Sanity is a golden apple with no shoelaces.";
Quotation[2] = "Repent! The end is coming, $9.95 at Amazon.";
Quotation[3] = "Honesty blurts where deception sneezes.";
Quotation[4] = "Pastry satisfies where art is unavailable.";
Quotation[5] = "Delete not, lest you, too, be deleted.";
Quotation[6] = "O! Youth! What a pain in the backside.";
Quotation[7] = "Wishes are like goldfish with propellors.";
Quotation[8] = "Love the river's \"beauty\", but live on a hill.";
Quotation[9] = "Invention is the mother of too many useless toys.";


var Q = Quotation.length;
var whichQuotation=Math.round(Math.random()*(Q-1));
function showQuotation(){document.write(Quotation[whichQuotation]);}
showQuotation();
</script>

If anyone could help me get that array into another file and call it from that script I would really appreciate it.

Thanks guys!

Rowsdower!
12-15-2010, 07:20 PM
The easiest way is just to add that file to the header. At that point you can use the array of quotes just as if it were in the same script that was displaying it:


<html...

<script type="text/javascript" src="path/to/file.js"></script>

...</head>

That's the easiest way. But your question asked about doing this with javascript.

Doing it strictly from javascript methods you can create a script element and set it's src attribute to the target file, then insert the script element into the page. This dynamically does what my first suggestion does.

The third option is to pull the file in as a text string using AJAX (http request) and then parse the result looking for the quotes, then pick and display one.

Philip M
12-15-2010, 07:23 PM
Just a comment - ensure that your external .js file contains no HTML tags
(<script type = "text/javascript"> </script>).

var whichQuotation=Math.round(Math.random()*(Q-1));
Math.round() does not give true random distribution as 1-8 is selected more frequently than 0 or 9

Use instead
var whichQuotation = Math.floor(Math.random() * (Q)); // generates 0-9

But that does not prevent the same number being generated two or more times in succession.
Better to shuffle your array of quotations:-


<input type = "button" value = "Show next quote" onclick = "showNext()"><br>
<div id = "theQuote"></div>

<script type = "text/javascript">

var quoteArray = [];
quoteArray[0] = "Time is of the essence! Comb your hair.";
quoteArray[1] = "Sanity is a golden apple with no shoelaces.";
quoteArray[2] = "Repent! The end is coming, $9.95 at Amazon.";
quoteArray[3] = "Honesty blurts where deception sneezes.";
quoteArray[4] = "Pastry satisfies where art is unavailable.";
quoteArray[5] = "Delete not, lest you, too, be deleted.";
quoteArray[6] = "O! Youth! What a pain in the backside.";
quoteArray[7] = "Wishes are like goldfish with propellors.";
quoteArray[8] = "Love the river's \"beauty\", but live on a hill."; // note escape quotes
quoteArray[9] = "Invention is the mother of too many useless toys.";

function randOrd(){return (Math.round(Math.random())-0.5); }
quoteArray.sort(randOrd);

var count = 0;
function showNext() {
document.getElementById("theQuote").innerHTML = quoteArray[count];
count ++;
if (count >9) {
quoteArray.sort(randOrd); // shuffle the array again
count = 0;
}
}

</script>


Take my advice, I don't use it anyway.

TheDave
12-15-2010, 07:40 PM
Hi Guys, Thank you very much for the replies,

I think Im doing something wrong, Ive created the .js file with my array and placed the code into the page but not getting anything, this is what ive done.

in the .js file I have
var Quotation=new Array()

Quotation[0] = "...and all the quotes

In the HTML head I have:

<script src="../global/java/dyk.js" type="text/javascript"></script>

then in the body I have

<script language="JavaScript">
var Q = Quotation.length;
var whichQuotation=Math.round(Math.random()*(Q-1));
function showQuotation(){document.write(Quotation[whichQuotation]);}
showQuotation();
</script>

What am I misisng?

Thanks again guys!

Philip M
12-15-2010, 07:50 PM
Are you sure that you .js file is in the right directory? Add an alert to check that it has loaded.

var Quotation=new Array()
alert ("js File loaded");

Did you read my advice to use
var whichQuotation = Math.floor(Math.random() * Q); // generates 0-9
rather than Math.round()?

<script language=javascript> is long deprecated and obsolete. Use <script type = "text/javascript"> instead.

TheDave
12-15-2010, 08:02 PM
I just noticed your edit now, I changed the whichquotation as you suggested, I do have a question though, I have more then 9 quotations right now, does that method only generate 0-9?

I tried adding the alert (it goes in the .js file right?) and nothing seemed to happen but Im positive its in the correct directory.

There is another <script> item in the header thouhg (a traffic tracking script), could that be causing the issue?

Philip M
12-15-2010, 08:53 PM
I just noticed your edit now, I changed the whichquotation as you suggested, I do have a question though, I have more then 9 quotations right now, does that method only generate 0-9?

I tried adding the alert (it goes in the .js file right?) and nothing seemed to happen but Im positive its in the correct directory.

There is another <script> item in the header though (a traffic tracking script), could that be causing the issue?

No, if Q is the array length, it will generate evenly distributed random numbers from 0 to Q-1. Here Q is 10 (so generates 0-9 which are the array indices) unless you change the number of quotations.

If you added the alert, and nothing happened, then it must be in the wrong directory (or the src reference is wrong).

No, another script would not normally interfere unless there is duplication of function and/or variable names (not likely).

TheDave
12-15-2010, 09:25 PM
There must be something else, Ive even tried setting the path to the exact url of the .js file and still nothing.

Do I need onload in the body tag perhaps? Or should I call the .js dynamically (not sure how)

Rowsdower!
12-15-2010, 09:40 PM
It would be easier to debug this if we could see the test page you are working on. Can we have a link?

TheDave
12-15-2010, 10:20 PM
its not incorportated into the website yet because it doesnt work, but the code Im using is exactly as it appears above.

Theres no buttons or anything though and I need the script to display each time the page is loaded so wouldnt I need an onLoad in the body tag? I think Ive had issues with javascrits it the past and this is what solved it but Im not sure how to write the onload, do I just call the function?

Old Pedant
12-15-2010, 10:40 PM
No, you should not need the <body onload> for this. I can't see how it would do anything but get in the way.

Try this with a stripped down page. With nothing in it but *exactly* what is needed.


<html>
<head>
<script src="../global/java/dyk.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
document.write( Quotation[ Math.floor( Math.random() * Quotation.length ) ] );
</script>
</body>
</html>

If that doesn't work, show us the *EXACT* contents of the "dyk.js" file.

Old Pedant
12-15-2010, 10:44 PM
WTH. The "dyk.js" file should contain exactly and only the following. *NOTHING ELSE AT ALL*.


var Quotation=new Array() // do not change this!

Quotation[0] = "Time is of the essence! Comb your hair.";
Quotation[1] = "Sanity is a golden apple with no shoelaces.";
Quotation[2] = "Repent! The end is coming, $9.95 at Amazon.";
Quotation[3] = "Honesty blurts where deception sneezes.";
Quotation[4] = "Pastry satisfies where art is unavailable.";
Quotation[5] = "Delete not, lest you, too, be deleted.";
Quotation[6] = "O! Youth! What a pain in the backside.";
Quotation[7] = "Wishes are like goldfish with propellors.";
Quotation[8] = "Love the river's \"beauty\", but live on a hill.";
Quotation[9] = "Invention is the mother of too many useless toys.";

Or you could even write it more compactly and make it easier to edit:


var Quotation = [
"Time is of the essence! Comb your hair.",
"Sanity is a golden apple with no shoelaces.",
"Repent! The end is coming, $9.95 at Amazon.",
"Honesty blurts where deception sneezes.",
"Pastry satisfies where art is unavailable.",
"Delete not, lest you, too, be deleted.",
"O! Youth! What a pain in the backside.",
"Wishes are like goldfish with propellors.",
"Love the river's \"beauty\", but live on a hill.",
"Invention is the mother of too many useless toys."
];

jmrker
12-16-2010, 03:32 AM
its not incorportated into the website yet because it doesnt work, but the code Im using is exactly as it appears above.
...


:confused: Question: Are you working on the problem locally (your computer)
or are you testing on the server? If on server, make sure both the HTML and JS external file have been give the permissions to be read by the browsers.

TheDave
12-16-2010, 04:26 AM
Well I would be lying if I said this wasnt getting frustrating.

I did as Old Pedant said and just threw it on a blank test page and still nothing, I even put the .js file right in the directory of the file and it still doesnt work.

Here is exactly whats in the .js file, are there some characters that I used? I read over it and I cant find the error.

var Quotation=new Array()
Quotation[0] = "A female kitten can become pregnant at 5 months old. Cats can have 3
litters per year At an average of 4 kittens per litter that’s a lot of cats !";
Quotation[1] = "Scientists believe that the size and the spacing of a domestic cat’s fangs are
designed to match the skeletal structure of the standard house rodent – making
it the perfect mouse-killing machine.";
Quotation[2] = "Cats’ ears allow them to hear sounds two octaves higher that what humans can
detect.";
Quotation[3] = "An average of 24 deeply embedded whiskers divided equally on either side of
the face act as sensory detectors for the cat, providing information about its
surroundings.";
Quotation[4] = "Cats can jump up to 6 times their own height.";
Quotation[5] = "Cats prefer to view the world from a high vantage point where they can spy
possible vermin and stay out of harms way.";
Quotation[6] = "Cats enjoy being stroked because the action mimics the sensation of being
licked by their mother when they were kittens.";
Quotation[7] = "The cat’s range of peripheral vision is up to about 285 degrees. The human
range is well below 180 degrees.";
Quotation[8] = "Cats have difficulty seeing things that are directly under their noses – which is
why sometimes they have difficulty finding morsels of food you drop on the
floor for them.";
Quotation[9] = "A cat does not scratch an object to \“sharpen his claws\”. Rather to rid himself
of old claw sheaths, and to exercise the muscles associated with the retracting of
the claws.";
Quotation[10] = "Kittens start purring at about a week old. Purring is a means of
communication between kittens and their mother.";
Quotation[11] = "As long as they are neutered , have shelter and adequate food feral cats cat live
as healthy and long a life as pet cats.";
Quotation[12] = "Feral cats are NOT the reason song birds are disappearing. While fewer cats
are always better for bird populations, the overwhelming cause of wildlife
depletion is destruction of natural habitat by humans.";
Quotation[13] = "The \“wagging\” of a cats tail indicates indecision.";


and here is exactly whats in the test page:

<html>
<head>
<script src="dyk.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
document.write( Quotation[ Math.floor( Math.random() * Quotation.length ) ] );
</script>
</body>
</html>

Old Pedant
12-16-2010, 05:36 AM
Ummm...you can *NOT* have a line break in the MIDDLE of a quoted string in JavaScript.

You have (first of many examples):



Quotation[0] = "A female kitten can become pregnant at 5 months old. Cats can have 3
litters per year At an average of 4 kittens per litter that’s a lot of cats !";

with a line break before "litters".

It *MUST* be all on ONE LINE:


Quotation[0] = "A female kitten can become pregnant at 5 months old. Cats can have 3 litters per year At an average of 4 kittens per litter that’s a lot of cats !";

If you don't like long lines of code, you can break the line thus:


Quotation[0] = "A female kitten can become pregnant at 5 months old. "
+ "Cats can have 3 litters per year. "
+ "At an average of 4 kittens per litter that’s a lot of cats !";

That is, put the text on multiple physical lines, in multiple quoted string, and then append each line of text to the one before with the + operator.

And if you want the text to *appear* on multiple lines in the browser, you can add <br> to each physical line, thus:


Quotation[0] = "A female kitten can become pregnant at 5 months old.<br>"
+ "Cats can have 3 litters per year.<br>"
+ "At an average of 4 kittens per litter that’s a lot of cats !<br>";

TheDave
12-16-2010, 04:04 PM
Thank you! That was the problem, its always something stupid isnt it?

Thank you so much for all the help, I can finally move forward with this.

Cheers!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum