Monday 22 November 2010

jQuery: random quotes from a txt file

   


If you want to create random quotes, loading the text from an external file, jQuery and its GET command could be a simple a fast solution.
We can create a div tag that will be the target of the quote:
<table>
   <tr>
     <td valign="middle"><div align="right" class="quotes"></div></td>
   </tr>
 </table>

I like to put it inside a table and give it a proper style:
.quotes {
    font-family: Georgia, "Times New Roman", Times, serif;
    font-size: 14px;
    font-style: italic;
    color: #FFFFFF;
    text-decoration: none;
    height:40px;
    text-align: right;
    overflow: hidden;
    width: 400px;
    display:table-cell;
    vertical-align:middle;
}
The style is just an example. You can modify it according to your taste and needs.

To use jQuery, first of all include the library in the head of your page:
<script type="text/javascript" src="js/jquery.js"></script>
**Please change the src according to your jquery library path**
Then, add the following snippet:
jQuery(document).ready(function($) {
    $.get('quotes.txt', function(data) {
        var quotes = data.split("\@");
        var idx = Math.floor(quotes.length * Math.random());
        $('.quotes').html(quotes[idx]);
    });
});
The code, executed when the document is ready, will get the content of a txt file named quotes.txt, it will split the single quotes, it will generate a random number and insert the text in the quotes div.
The quotes.txt file contains all your quotes ending with a @ character. That is used to determine where the quote ends. An example of the txt file could be:
Because we're friends, I'm gonna tell you something nobody else knows. I'm homophobic.@
Cookies, everyone! Nourishment is most important in the morning.@
Objection, your Honor. You can't preface your second point with "first of all."@
Denny Crane@
You know what I'm going to do, Brian, just to show you there are no hard feelings? I'm going to sleep with your wife.@
Did something happen? Was I in the room when it happened?

That's all folk. Enjoy!

19/01/2011 UPDATE: If you use WordPress see this post!

27 comments:

  1. Hi, i'm trying to add the author, but I can't figure how to do that. And how I can style the author as well..

    ReplyDelete
  2. You can add the Author just before the @. You can style it using appropriate html tags.

    ReplyDelete
  3. This may be just what I'm looking for! Thanks!

    ReplyDelete
  4. Thank you Nick. I am happy to hear that you found it useful!

    ReplyDelete
  5. Great code!
    Remember to specify the full path of the document 'quotes.txt' like this:
    $.get('/the/full/path/to/your/file/quotes.txt', function(data) {
    ...

    Hope it helps -;)

    ReplyDelete
  6. Yes, the full path is necessary when the two files are not staying in the same place.
    Thanks for pointing that out.

    ReplyDelete
  7. Hi,

    Can you help me to tell about how to add manualrandom text?
    I'm using plugin ArrJS
    for example, i want to place in header

    ReplyDelete
  8. I don't understand your question...

    ReplyDelete
  9. sorry, i not too good in english language

    I am using plugin ArrJS (create by http://design.bybrandon.net/) for my blog (wordpress)

    But, my problem was resolved.

    Regard.

    ReplyDelete
  10. OK! I'm happy you found a solution in any case.

    ReplyDelete
  11. Hey friend, I did everything you said, but can't get this thing running - the site remains empty. Please, would you have a look at my testfile?

    Is there anything wrong? The jquery.js file is in the same folder, just as the quotes.txt. Why is there no output?

    ReplyDelete
  12. Hello Robert,

    it seems to me that your quotes.txt file is empty. Please check if it contains something.
    Second thing, please check the path to your quotes.txt file.

    ReplyDelete
  13. Robert,
    another thing, you set the color rule for your text to white and the the background color is white as well...

    ReplyDelete
  14. hey there. this seems so simple but for some reason it's not working for me. if you go to http://dangerboydesign.com/clients/psychick/about/index.htm you can see a red outlined (for emphasis) blockquote region that is empty. it should have a quote displayed. the path to the .txt file is absolute, and the script previews in Dreamweaver's local Live View, but not in a browser. i can't see any reason for this. any ideas?

    ReplyDelete
  15. Hello Morgan,
    I've visited you page. Look for your code:
    <blockquote class="quoted"></blockquote>
    and try to make it a div:
    <div class="quoted"></div>
    That could be one problem. However, just to be sure, put your 'quotes.txt' file into the 'http://dangerboydesign.com/clients/psychick/about' folder, and then change your snippet to $.get('quotes.txt', function... and so on.
    Last thing, I see you have styled blockquote and .quoted. Blockquote has a background image. I'm not sure it will work like that.
    Firebug is telling me that your AJAX request is not working. Move your quotes.txt file as said...
    Hope that helps.

    ReplyDelete
  16. thanks for replying, marco. i've already tried putting the quote class on a div rather than on the blockquote, and it made no difference. neither did removing the background styling from the blockquote or moving the txt file. besides, i want this snippet to appear on most pages, so would need an absolute path to work. guess i'll have to try another random quote method.

    ReplyDelete
  17. Morgan, it is highly probable that other solutions won't work as well. It seems that the ajax requestes are not completed (as I can see from FireBug). I'm sorry about that...

    ReplyDelete
  18. Ruben Fernandes3 March 2012 at 22:07

    looks like it doesn't work on chrome, it shows only on Dreamweaver and IE :/

    ReplyDelete
    Replies
    1. It does work on Chrome, IE, FireFox, Opera amd Safari, as far as I can see. You need JavaScript enabled, of course.
      By the way, remember that Dreamweaver is not a browser.

      Delete
  19. it DOES NOT WORK in CHROME even with javascript enabled.

    did anyone find a solution because i would really like to use this. Thanks!

    ReplyDelete
  20. Hi Again,

    It appears that CHROME DOES WORK but only from server since Chrome doesnt allow files to be loaded locally for security purposes.

    But you can still be of much help. I would like the quotes to change automatically after 10seconds by means of fading.
    (something like this: http://leo.dolcepixels.com/learning/jquery/snippets/random-text-from-array-with-jquery-v-2/)

    ReplyDelete
    Replies
    1. Use some sort of timer to trigger the function... It's the only thing that I can think of at the moment.

      Delete
  21. Yup - debuging in Chrome says:

    XMLHttpRequest Origin null is not allowed Access-Control-Access-Allow for file:///

    But, don't worry - when you put it on server, it will work like a charm.

    Marco, thanks for this tip.

    ReplyDelete
  22. Thank you for this tutorial! I had been looking for it for a while now. The explanation is really simple for a beginner like me. What I wanted to ask is, is it going to show the quotes just on the homepage? Or on every permalink?

    ReplyDelete
    Replies
    1. Sorry Soumil, What do you mean by "every permalink"?

      Delete
  23. I know this is pretty old but it help me out, thank you. I will also add one small change.
    change: var idx = Math.floor(quotes.length * Math.random());
    to: var idx = Math.floor((quotes.length-1) * Math.random());
    add -1 to quotes.length and wrap it in parenthesis otherwise you will get an empty div occasionally.

    ReplyDelete
  24. That is cool! Is there a way to make it choose from different txt file based on the day? For example if it is Friday then it will pick a random quote from friday.txt
    Best Regards

    ReplyDelete

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.