Search code examples
jqueryarraysrandomquotationsbigcartel

jQuery random blockquote


I've spent the past 2 hours looking for and testing various solutions to this problem but to little success so I'm resigned to asking for help.

I would like to build an array of quotes which each have citations and and a link, to be pulled at random. I don't need any thing more than for them to change upon page refresh.

However, I have some pretty tasty CSS to style blockquote and cite.

Here's some example HTML to illustrate how the content from the array would fit within a quote:

<blockquote>
  <p>A line of oversize watches that can offer many of the attributes of premium luxury watches at an affordable price.
  </p>
  <cite>&mdash; 
    <a href="http://www.horozima.com/2012/07/terranaut-xl-50mm.html" target="_blank">Horozima
    </a>
  </cite>
</blockquote>

The intended location for this code is a Big Cartel product (template) page with automatically generated content for each product. So, without some randomizing JS the same quote would be on every product page.


Solution

  • Execute JavaScript on DOMReady to use the random() function to generate a random number. If you multiply this number by a value you will get a random number between 0 and the value (but not including the value itself). If you put the quotes into a JSON array, you can use the array's .length property for the value you multiply by since the number of items in the array is one larger than the index of the last item. This will generate a random number that is one of the indexes of the array.

    After this, use jQuery's text() function to replace the text of the paragraph and citation tags to display the quote you randomly selected.

    Here is an example: http://jsfiddle.net/sWvGp/

    HTML:

    <blockquote id="randomquote">
        <p></p> <cite>&mdash; <a href="#" target="_blank"></a></cite>
    </blockquote>
    

    Javascript:

    var myQuotes = [{
        quote: "To err is human; to forgive, divine.",
        cite: "Alexander Pope",
        url: "http://www.example.com"
    }, {
        quote: "Reports of my death have been greatly exaggerated.",
        cite: "Mark Twain",
        url: "http://www.example.com"
    }, {
        quote: "A line of oversize watches that can offer many of the attributes of premium luxury watches at an affordable price.",
        cite: "Horozima",
        url: "http://www.horozima.com/2012/07/terranaut-xl-50mm.html"
    }];
    
    var randomQuote = Math.floor(Math.random() * myQuotes.length)
    
    $('p', '#randomquote').text(myQuotes[randomQuote].quote);
    $('cite a', '#randomquote').attr('href', myQuotes[randomQuote].url).text(myQuotes[randomQuote].cite);