Building A Movie Quote Randomizer with Vanilla JS and Mashape API
Using application user interfaces (APIs) can be a bit tricky and confusing to beginner developers who are building an app for the first time. This tutorial aims at giving a brief and concise directive to building an app with plain JavaScript and jQuery while making API calls.
Before we begin, it’s important to highlight what we expect of our app. For a movie quote randomizer which can generate a random quote at will, expectations are as follows:
- A user can click on a button and generate a random quote with the quotes author from a famous movie.
- A user can click on another button to tweet out the quote generated.
- For every random quote that comes up, the background color of the paragraph shall also change (transitioning slowly) to a random color.
Getting the API
The first step usually is to sign up with a reliable API service provider. In this case, we shall be relying on Mashape to help us with what we need, which is an API that when called, provides an object consisting of several arrays of movie quotes and their authors.
Making an AJAX Request
Next, we shall use jQuery to make an AJAX request to Mashape. The good thing is that the Uniform Resource Locators (URL) to Mashape’s APIs are already Cross-Origin Resource Sharing (CORS) enabled. This prevents issues of domain conflicts when making API calls.
Making the AJAX request is quite simple and straightforward:
var loadquote = function() {
$.ajax({
type: "GET",
url: "https://andruxnet-random-famous- quotes.p.mashape.com/?cat=movies&count=1",
data: {},
dataType: 'json',
success: function(data) {
$("#quote-text").html('"' + data.quote + '"');
$("#quote-author").html('—' + ' ' + data.author);
},
error: function(err) { alert("Internet Disconnected!"); },
beforeSend: function(xhr) {
xhr.setRequestHeader("X-Mashape-Authorization", "Bk47jF0aCnmshsTi1VQAyxueTH2ap1BJxjejsnw9wHKPr2OmG4");
}
});
};
As you might have noticed, using jQuery, we assigned our HTML paragraphs; quote-text
and quote-author
to fetch raw data from the “quote” and “author” keys in our data object.
We also embedded the entire AJAX call in a function and assigned it to a variable loadquote
for easier accessibility and manipulation. The setRequestHeader()
method contains our Mashape Authorization as well as our key (every user has a unique key).
Creating the Random Background Color Property
As we mentioned earlier, we want our background to change whenever a new quote comes up. One way to do this is by making use of the Math.floor()
and Math.random()
functions.
Creating a variable called “backgroundChange”, we then proceed to assign a function to it that tells our app what to do with the background color:
var backgroundChange = function() {
x = Math.floor(Math.random() * 256);
y = Math.floor(Math.random() * 256);
z = Math.floor(Math.random() * 256);
backgroundRGB = "rgb(" + x + "," + y + "," + z + ")";
document.getElementById("quote-design").style.backgroundColor = backgroundRGB;
}
Creating the Transition Effect
Creating the transition effect is pretty easy, all we have to do is create a variable and assign our function which gets the HTML element where we want the transition to be and styles it accordingly:
var transition = function() {
document.getElementById("quote-design").style.transition = "all 2s";
}
Adding a button that tweets the quote
For our “twitter-share” button, we create a button in our HTML page and then use jQuery to manipulate it.
The tweet button is powered by a Twitter API that tweets quotes. For the button to function properly, it’s important that we embed our jQuery method in our AJAX request:
var loadquote = function() {
$.ajax({
type: "GET",
url: "https://andruxnet-random-famous- quotes.p.mashape.com/?cat=movies&count=1",
data: {},
dataType: 'json',
success: function(data) {
$("#quote-text").html('"' + data.quote + '"'); $('#twitter-share-button').attr('href', 'https://twitter.com/intent/tweet?text=' + '"' + data.quote + '"' + ' ' + ' ' + ' ' + ' \u2014' + ' ' + data.author).attr('target', '_blank'); // embed the method HERE
}, error: function(err) { alert("Internet Disconnected!"); },
beforeSend: function(xhr) {
xhr.setRequestHeader("X-Mashape-Authorization", "Bk47jF0aCnmshsTi1VQAyxueTH2ap1BJxjejsnw9wHKPr2OmG4");
}
});
};
Adding a button that changes the quote as well as transitions the background color
Now for the final part, creating the most important button in the app! Having gotten this far, this should be no trouble to us.
To create the button, we simply insert a button element in our HTML section. We have the option of using the addEventListener()
method in JavaScript or using .on()
method in jQuery. We’ll go with the latter as it brings a lot of consistency to our API and simplifies our code base:
$("#change-quote").on("click", function() {
loadquote();
backgroundChange();
transition();
})
As seen above, we embedded our loadquote()
, backgroundChange
and transition()
functions in our change-quote
jQuery function. Once the button is clicked, these three functions will take place simultaneously.
There! We have successfully built a Movie Quote Randomizer, with the help of APIs, a jQuery library and best practices — and we kept our code clean and concise. For further details about the app, you can check it out here.
If you liked this article, be sure to recommend it as that would mean a lot to me Thanks. 🙂