Skip to content

Instantly share code, notes, and snippets.

@duggiemitchell
Last active December 24, 2015 16:49
Show Gist options
  • Save duggiemitchell/d559633331778027f5bb to your computer and use it in GitHub Desktop.
Save duggiemitchell/d559633331778027f5bb to your computer and use it in GitHub Desktop.
Random Quote Generator using jQuery Event Handlers

Random Quote Generator

First create arrays as global variables. I was informed global variables should be avoided for they can cause problems, especially in a project with concurrency. But seeing this project is fairly simple, we can make this exception. We'd obviously like to have more quotes to choose from, but if you want to see the project in action check it out on my portfolio.

var happyQuotes = ["I am a happyQuote!","I too am a happyQuote!;]; var lostQuotes = [" I am lost!"," I too am lost!";`"]; var scaredQuote = ["I am sooo scared!" , "I second that... being scared!"]; var sadQuote = [```"Fear is the mind killer.","...doesn't stop my fear"];

getRandomNumberNumber accepting min and max as arguments function getRandomNumber(min, max){ ` return Math.floor(Math.random() * (max - min + 1)) + min;} Nested function usingswitch ``as apposed to ``if else`` statement; less cluttered and much easier to read ```function getRandomQuote(type){`` `` var quote;``

    switch(type) {
      case "happy":
        quote = happyQuotes[getRandomNumber(0, happyQuotes.length)];
        break;
      case "sad":
        quote = sadQuotes[getRandomNumber(0, sadQuotes.length)];
        break;
      case "lost":
        quote = lostQuotes[getRandomNumber(0, lostQuotes.length)];
        break;
      case "scared":
        quote = scaredQuotes[getRandomNumber(0, scaredQuotes.length)];
        break;
    }``
    
  return quote; 
  }

Here comes the Jquery $( document ).ready(function() {

//The click event handler is two-fold. Must first match the feeling attribute from HTML document with the apporiate quote. Second, the quoteSection is hidden in CSS so it must display the random quote in the quoteSection div $("button").on( "click", function(e) {

      var quote = getRandomQuote(e.target.getAttribute('feeling'));
    	$('.quoteSection').text(quote);
      $('.quoteSection').show('slow');
  });

  ``});``
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment