Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 16
  1. #1
    New to the CF scene
    Join Date
    Dec 2010
    Posts
    7
    Thanks
    3
    Thanked 0 Times in 0 Posts

    How to call an array thats in a different file

    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!

  • #2
    Senior Coder Rowsdower!'s Avatar
    Join Date
    Oct 2008
    Location
    Some say it's everything.
    Posts
    2,027
    Thanks
    5
    Thanked 397 Times in 390 Posts
    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:

    Code:
    <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.
    The object of opening the mind, as of opening the mouth, is to shut it again on something solid. –G.K. Chesterton
    See Mediocrity in its Infancy
    It's usually a good idea to start out with this at the VERY TOP of your CSS: * {border:0;margin:0;padding:0;}
    Seek and you shall find... basically:
    validate your markup | view your page cross-browser/cross-platform | free web tutorials | free hosting

  • Users who have thanked Rowsdower! for this post:

    TheDave (12-16-2010)

  • #3
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,919
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    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:-

    Code:
    <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.
    Last edited by Philip M; 12-15-2010 at 07:44 PM.

  • Users who have thanked Philip M for this post:

    TheDave (12-16-2010)

  • #4
    New to the CF scene
    Join Date
    Dec 2010
    Posts
    7
    Thanks
    3
    Thanked 0 Times in 0 Posts
    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!

  • #5
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,919
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    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.
    Last edited by Philip M; 12-15-2010 at 07:54 PM.

  • #6
    New to the CF scene
    Join Date
    Dec 2010
    Posts
    7
    Thanks
    3
    Thanked 0 Times in 0 Posts
    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?

  • #7
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,919
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Quote Originally Posted by TheDave View Post
    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).

  • #8
    New to the CF scene
    Join Date
    Dec 2010
    Posts
    7
    Thanks
    3
    Thanked 0 Times in 0 Posts
    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)
    Last edited by TheDave; 12-15-2010 at 09:33 PM.

  • #9
    Senior Coder Rowsdower!'s Avatar
    Join Date
    Oct 2008
    Location
    Some say it's everything.
    Posts
    2,027
    Thanks
    5
    Thanked 397 Times in 390 Posts
    It would be easier to debug this if we could see the test page you are working on. Can we have a link?
    The object of opening the mind, as of opening the mouth, is to shut it again on something solid. –G.K. Chesterton
    See Mediocrity in its Infancy
    It's usually a good idea to start out with this at the VERY TOP of your CSS: * {border:0;margin:0;padding:0;}
    Seek and you shall find... basically:
    validate your markup | view your page cross-browser/cross-platform | free web tutorials | free hosting

  • #10
    New to the CF scene
    Join Date
    Dec 2010
    Posts
    7
    Thanks
    3
    Thanked 0 Times in 0 Posts
    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?

  • #11
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,200
    Thanks
    75
    Thanked 4,342 Times in 4,308 Posts
    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.
    Code:
    <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.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #12
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,200
    Thanks
    75
    Thanked 4,342 Times in 4,308 Posts
    WTH. The "dyk.js" file should contain exactly and only the following. *NOTHING ELSE AT ALL*.
    Code:
    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:
    Code:
    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."
        ];
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #13
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,077
    Thanks
    38
    Thanked 498 Times in 492 Posts

    Question

    Quote Originally Posted by TheDave View Post
    its not incorportated into the website yet because it doesnt work, but the code Im using is exactly as it appears above.
    ...
    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.

  • #14
    New to the CF scene
    Join Date
    Dec 2010
    Posts
    7
    Thanks
    3
    Thanked 0 Times in 0 Posts
    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>

  • #15
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,200
    Thanks
    75
    Thanked 4,342 Times in 4,308 Posts
    Ummm...you can *NOT* have a line break in the MIDDLE of a quoted string in JavaScript.

    You have (first of many examples):

    Code:
    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:
    Code:
    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:
    Code:
    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:
    Code:
    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>";
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    TheDave (12-16-2010)


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •