Random Quote Generator

In this example below you will see how to do a Random Quote Generator with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by TurnipEntropy, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright TurnipEntropy ©

Technologies

  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>Random Quote Generator</title>
  
  
  <link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css'>

      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <div class="container">
  <h2>WARNING:</h2>
  <h4>These quotes are not filtered for depressing, explicit, or potentially-triggering material. They are selected at random from wikiquote</h4>
  <button id="gen-quote">Generate quote</button>
  <div id="quote"></div>
</div>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>

  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/TurnipEntropy/random-quote-generator-XRVwGQ */
body{
  background:#abc;
}

/*Downloaded from https://www.codeseek.co/TurnipEntropy/random-quote-generator-XRVwGQ */
var url = "https://en.wikiquote.org/w/api.php";
function randInt(maxVal){
  return Math.floor(Math.random() * maxVal);
}
var currentPageId = 0;
function grab(x){
  currentPageId = x;
}

$.ajax({
  url:url,
  dataType:"jsonp",
  data:{
    format:"json",
    action:"parse",
    redirects:"",
    prop:"links",
    pageid:"161415"
  },
  success: function(result){
  }

});

//get random quote from a random person

function getRandomQuote(pageid, success){
  var getRandQuote = function(quotes){
    var ind = Math.floor(Math.random() * quotes.quotes.length);
    success({titles:quotes.titles,
            quotes: quotes.quotes[ind]});
  }
  
  var getQuotes = function(pageid, sections){
    var ind = Math.floor(Math.random() * sections.sections.length);
    getQuotesForSection(pageid, sections.sections[ind], getRandQuote);
  }
  
  getSectionsForPage(pageid, function(sections){
    getQuotes(pageid, sections);
  });
}

//Get random name from the randomly
//selected list
function getRandomName(pageid, success){
  $.ajax({
    url:url,
    dataType:"jsonp",
    data:{
      format:"json",
      action:"parse",
      prop:"links",
      pageid:pageid
    }
  }).then(function(result){
    var links = result.parse.links;
    var exception = "List of";
    links = links.filter(function(i){
      return !i["*"].includes(exception);
    });
    var pageind = randInt(links.length);
    var link = links[pageind]["*"];
    getPageId(link, function(data){
      success(data);
    });
  });
}

//Get the possible lists of lists
//of names (split up a, b, e-f, etc.)
function goToRandomListOfPeople(success){
  $.ajax({
    url:url,
    dataType:"jsonp",
    data:{
      format:"json",
      action:"parse",
      prop:"links",
      pageid:"94"
    }
  }).then(function(result){
    var links = result.parse.links;
    var exception = "Category";
    links = links.filter(function(x){
      return !x["*"].includes(exception);
    });
    var pind = randInt(links.length);
    var link = links[pind]["*"];
    //now I need to grab the pageid
    //for the link so I can go there
    //and grab its links to go to a 
    //random person to then grab a random
    //quote
    link = link.replace("-", "\u2013");
    getPageId(link, function(data){
     success(data);
    });
  });
}

function getPageId(pageTitle, success){
  promise = $.ajax({
    url:url,
    dataType:"jsonp",
    data: {
      action:"query",
      redirect:"",
      format:"json",
      titles:pageTitle
    }
  }).then(function(result){
    var pages = result.query.pages;
    var keys = Object.keys(pages);
    success(pages[keys[0]].pageid);
  });
}

$("#gen-quote").on("click", function(){
  var result = {};
   goToRandomListOfPeople(function(data){
     getRandomName(data, function(data2){
       getRandomQuote(data2, function(quote){
         $("#quote").html("<p>" + quote.quotes + "</p><br><br><p>&nbsp&nbsp-" + quote.titles + "</p>");
       })
     });
   });
});


//from wikiquotes api by natetyler
function getSectionsForPage(pageId, success, error) {
    $.ajax({
      url: url,
      dataType: "jsonp",
      data: {
        format: "json",
        action: "parse",
        prop: "sections",
        pageid: pageId
      },

      success: function(result, status){
        var sectionArray = [];
        var sections = result.parse.sections;
        for(var s in sections) {
          var splitNum = sections[s].number.split('.');
          if(splitNum.length > 1 && splitNum[0] === "1") {
            sectionArray.push(sections[s].index);
          }
        }
        // Use section 1 if there are no "1.x" sections
        if(sectionArray.length === 0) {
          sectionArray.push("1");
        }
        success({ titles: result.parse.title, sections: sectionArray });
      },
      error: function(xhr, result, status){
        error("Error getting sections");
      }
    });
  };


function getQuotesForSection(pageId, sectionIndex, success, error) {
    $.ajax({
      url: url,
      dataType: "jsonp",
      data: {
        format: "json",
        action: "parse",
        noimages: "",
        pageid: pageId,
        section: sectionIndex
      },

      success: function(result, status){
        var quotes = result.parse.text["*"];
        var quoteArray = []

        // Find top level <li> only
        var $lis = $(quotes).find('li:not(li li)');
        $lis.each(function() {
          // Remove all children that aren't <b>
          $(this).children().remove(':not(b)');
          var $bolds = $(this).find('b');

          // If the section has bold text, use it.  Otherwise pull the plain text.
          if($bolds.length > 0) {
            quoteArray.push($bolds.html());
          } else {
            quoteArray.push($(this).html());
          }
        });
        success({ titles: result.parse.title, quotes: quoteArray });
      },
      error: function(xhr, result, status){
        error("Error getting quotes");
      }
    });
  };

Comments