...

View Full Version : Using a single external file with two different blocks of code



BevansDesign
09-30-2008, 02:24 AM
I have 2 arrays I've placed in an external file called "quotes.js". It's your basic random quote generator thing.


quotes = new Array(2);
speakers = new Array(2);
quotes[0] = "Quote 1.";
speakers[0] = "Who Said It 1";
quotes[1] = "Quote 2.";
speakers[1] = "Who Said It 2";

//mark
index = Math.floor(Math.random() * quotes.length);
document.write("\n");
document.write("\""+quotes[index] + "\"<br/>");
document.write("<h3>\- "+speakers[index]+"</h3>");

I call it into my page with this:

<script SRC="quotes.js" language="javascript"></script>

That works fine.

However, I'd like to move the code in quotes.js (from "//mark" down) to a separate file so I can use my two arrays in two different files.

In one, I just want to display a random quote using this code:

index = Math.floor(Math.random() * quotes.length);
document.write("\n");
document.write("\""+quotes[index] + "\"<br/>");
document.write("<h3>\- "+speakers[index]+"</h3>");

But in another file, I want to use this code, which displays every quote in the array at once.

for (i=0;i<quotes.length;i++)
{
document.write(quotes[i] + "<br >");
document.write(speakers[i] + "<br ><br>");
}

My problem is that I don't know how to reference the data in the external JS file with these two blocks of code. The goal is that I'll only have to edit the single quotes.js file to update both the random quote page and the quote list page. I could just make two JS files, but what fun is that?

I tried to find a solution to this on Google, but unfortunately I didn't come up with anything. I'm not very familiar with Javascript, so it's pretty likely that there's a term for all of this that would've helped me immediately.

I'm guessing that what I'm looking for is just a simple command that says "look at quotes.js".

I appreciate any help you can give.

rnd me
09-30-2008, 02:32 AM
quotes = new Array(2);
speakers = new Array(2);
quotes[0] = "Quote 1.";
speakers[0] = "Who Said It 1";
quotes[1] = "Quote 2.";
speakers[1] = "Who Said It 2";

function printSingle(){
index = Math.floor(Math.random() * quotes.length);
document.write("\n");
document.write("\""+quotes[index] + "\"<br/>");
document.write("<h3>\- "+speakers[index]+"</h3>");
}

function printAll(){
for (i=0;i<quotes.length;i++){
document.write(quotes[i] + "<br >");
document.write(speakers[i] + "<br ><br>");
}
}


when /where ever you want one: printSingle().
when /where ever you want many: printAll().

you can put the functions anywhere.
just make sure your data (quotes + speakers) comes before calling the function.

BevansDesign
09-30-2008, 03:03 AM
Ah, cool. I knew it'd be something easy like that. I've been trying to learn this stuff for years, but the best I can do is modify existing code. I guess this is why I'm a designer, not a programmer.

Thanks a bunch!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum