How to create a Random Quote Machine using JQuery.

Random-Quote-Machine

On this post I will show you how to create a very simple Application that generates a Random quote using JQuery and an API (Application programming Interface). This is one of the projects for freecodecamp, a free online boot camp for front-end development. This app will generate a random quote once the user clicks the next button or share it to twitter if the share button is clicked. As an extra functionality, we will make the background color change on each click.

1. HTML markup.

First of all, let’s create a container for all of our application, I will be using bootstrap for quick styling. Inside this div, we will have two p tags with the id “quote” and “author” that will output the respective information and two buttons with the id’s “getquote” and “share”. It is important to put an id on each element we need for manipulating or accessing the DOM.

<div class="container">
    <div class="row">
        <div class="col-xs-12">
            <p id="quote"></p>
            <p id="author"></p>
        </div>
    </div>
    <div class="row">
        <ul class="list-inline">
         	<li>
         	  <a id="getquote" 
                   class="btn btn-default" href="#">Next
              </a>
            </li>
         	<li>
         	  <a id="share" 
                   class="btn btn-default" href="#">Share
              </a>
            </li>
        </ul>
    </div>
</div>

2. Quick CSS Styling

Add some style to make the application look better

body{

background-color: #4d1933;
color: white;
font-family: 'GidoleRegular'; 
}
.container{
	text-align: center;
	background-color: lightgray;
	max-width: 900px;
	margin-top: 7%;
	border-radius: 10px;
	padding: 25px 25px 25px 25px;
	background-color: inherit;
	border: solid 2px white;
	max-width: 700px;
}
#quote{
	line-height: 37px;
	font-size: 32px;
	font-stretch: 38px;
}
#author{
	line-height: 26px;
	font-size: 17px;
	font-stretch: 28px;
	text-align: right;
	padding-top: 20px;
	padding-right: 10px;
}

3. Adding the functionality with JQuery.

On this application we will be getting the information from an external source, using an API, which is an interface where different applications can communicate with each other. Using an API we can take advantage of other’s people database and get quick information instead of creating it ourselves.  For this project we will use forismatic , but there are many other quoting libraries you can use.

Inside a ready() function we will generate two global variables that will contain the author and the quote.

$(document).ready(function(){

    var quote;
    var author;

});

Then we are going to create a function called getQuote() that will generate an HTTP request to the URL, using Ajax. The main settings will be the url, where the API is located, jsonp necessary to bypass the cross-domain policies on web browsers and success, which contains the function to be called if the request succeeds. This function will have one parameter (response) which is going to output the data ( in this case we only need the Quote and the Author).

function getQuote(){

    $.ajax({
    
        url:'https://api.forismatic.com/api/1.0/',
        jsonp: 'jsonp',
        dataType: 'jsonp',
        data: {
            method: 'getQuote',
            lang:'en',
            format:'jsonp'
        },
        success: function(response){
        
            quote = response.quoteText;
            author = response.quoteAuthor;
            
           
        }
    });
}

The Author might be null and nothing will be displayed to the user. Let’s fix that by adding an If Else statement to display “unknown” in case it is null, Inside the function containing the “response” parameter.

 $('#quote').text("\" " + quote + "\" ");
            
        if(author){
        
             $('#author').text('-- '+ author);
        
        }else{
        
            $('#author').text('- unknown');
   }

Let’s continue by creating a simple click event handler for the button with the id name “getquote”
and call the function we previously created. Remember to use the preventDefault() function to stop the default action of an element from happening.

$('#getquote').on('click', function(event){

    event.preventDefault();
    getQuote();

});

We will do another event handler with the share button, but instead of executing the GetQuote function we will use the window.open() function to open a twitter page using the following url https://twitter.com/intent/tweet?text= plus the encodeURIComponent function and quote and author as the arguments. This will allow us to insert the quote and author directly to twitter.

$('#share').on('click', function(event){

    event.preventDefault();
    
    window.open('https://twitter.com/intent/tweet?text=' + encodeURIComponent(quote + ' -- ' + author));

});

Now our Application is fully functional but we can add more things to it. As an extra feature we can change the CSS color of the background each time the user clicks Next. To start with, let’s create an anonymous function and one array named colors containing the colors we want to display.

$(function() {

    getQuote();
    
    var colors = ['#4d0000', '#264d00', '#4d004d', '#001a4d'], color;

});

Below the array, create another click handler for the button with the id #getquote . To change the colors randomly we will make use of a Math.random() function multiplied by the colors array length. This will return a floating number, for that reason we will put this function inside another function called math.Floor(), which will return an integer. Store the function in a variable called randColor.

$('#getquote').click(function() {
    
    var randColor;

    randColor = colors[Math.floor(Math.random() * colors.length)];

});

We only want this function to run while the color variable in the array is equal to the RandColor of the output. Create a do while statement for that method.

$('#getquote').click(function() {
    
    var randColor;
    
    do {
    
        randColor = colors[Math.floor(Math.random() * colors.length)];
    
    } while (color == randColor);

});

Below the Do While statement we will select the HTML and body elements of the DOM and use the jQuery CSS function to change their color. As a first parameter of the function we will use the CSS “background-color” and as a second argument, the Randcolor variable we just created that will randomly output the colors we inserted each time a user clicks.

$('#getquote').click(function() {
    
    var randColor;
    
    do {
    
        randColor = colors[Math.floor(Math.random() * colors.length)];
    
    } while (color == randColor);
    
        $('html body').css('background-color', randColor);
        
        color = randColor;

});

The color change feature should be working now.

Complete JQuery code

$(document).ready(function(){

    var quote;
    var author;
    
    function getQuote(){
    
        $.ajax({
            
            url:'https://api.forismatic.com/api/1.0/',
            jsonp: 'jsonp',
            dataType: 'jsonp',
            data: {
                
                method: 'getQuote',
                lang:'en',
                format:'jsonp'
            },
            success: function(response){
            
                quote = response.quoteText;
                author = response.quoteAuthor;
                
                $('#quote').text("\" " + quote + "\" ");
                
                if(author){
                    
                     $('#author').text('-- '+ author);
                
                }else{
                    
                    $('#author').text('- unknown');
                    
                }
            }
        });
    }
    
    $('#getquote').on('click', function(event){
    
        event.preventDefault();
        getQuote();
        
    });
    
    $('#share').on('click', function(event){
    
        event.preventDefault();
        window.open('https://twitter.com/intent/tweet?text=' + encodeURIComponent(quote + ' -- ' + author));
    
    });
    
    $(function() {
    
        getQuote();
        
        var colors = ['#4d0000', '#264d00', '#4d004d', '#001a4d'],color;
        
        $('#getquote').click(function() {
        
            var randColor;
            
            do {
                
                randColor = colors[Math.floor(Math.random() * colors.length)];
            
            } while (color == randColor);
            
                $('html body').css('background-color', randColor);
                
                color = randColor;
        
        });
    });
});

You can see this Application live on Codepen

 


 

Leave a Reply

Your email address will not be published. Required fields are marked *