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:
I like to put it inside a table and give it a proper style:
To use jQuery, first of all include the library in the head of your page:
Then, add the following snippet:
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:
That's all folk. Enjoy!
19/01/2011 UPDATE: If you use WordPress see this post!
We can create a div tag that will be the target of the quote:
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:
**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!