This content originally appeared on DEV Community and was authored by Neha Gupta
Shakespeare may have been a genius, but one thing's for sure: he wasn't speaking our language. His ever-popular works (dramas and poems) make his unique language style live even today.
I've always been curious about how Shakespeare would've expressed my thoughts in his words. Have you been too??
Then you've come to the right place, my friend!
This is a vanillaJS project which uses API from https://funtranslations.com/ to translate English text into Shakespeare English.
Prerequisites | Basic understanding of HTML and CSS, an understanding of what JavaScript is. |
---|
Try out the app here
Source Code
In case you get lost while following along, you can grab the source code from here.
Let's begin!
Getting Started
To get started, we'll be using VSCode for writing our code. Create your first file with the name index.html for writing out HTML code.
In our Application, we have 3 basic elements:
- Input Field - to accept the user's input
- Translate Button - to create an event when the user clicks on the translate button.
- Output Field - to preview the translated text.
These 3 elements can be created as follows in HTML:
HTML code snippet - index.html
<body>
<input type="textarea" id="inputTxt" placeholder="insert your text">
<button id="translateButton">Translate!</button>
<p id="outputTxt"></p>
<script src='/scripts/app.js'></script>
</body>
Note: < script > tag is being used to bind this HTML file with the JavaScript file app.js.
Initialising variables to store our data
This section of the code sets up the variables we need to store the data our program will use.
In your app.js file, create the following variables:
JS code snippet - app.js
var inputElement = document.querySelector("#inputTxt"); // input element
var translateBtnElement = document.querySelector("#translateButton"); // button element
var outputElement = document.querySelector("#outputTxt"); // output element
var url="https://shakespeare.p.mashape.com/shakespeare.json"; //API URL
The first three variables inputElement
, translateBtnElement
, outputElement
are each made to store a reference to the form text input, translate button and output element in our HTML.
Our final variable url
is used to store the server's API call URL from where we obtain the translated data.
Here, we've used .querySelector()
function for selecting the particular id that we've already set in our index.html file.
To listen to the button click event we need to define an event handler function.
translateBtnElement.addEventListener("click", translateFunction);
Here,
-
click
- is the event -
translateBtnElement
- is the event listener -
translateFunction
- is the event handler/callback function.
After click
event has been fired on translateBtnElement
, the addEventListener()
method handles by calling translateFunction()
.
Before defining the translateFunction()
we need to get some basic knowledge about APIs.
What is an API?
API stands for Application Programming Interface, is a set of functions that allows applications to access data and interact with external software components, operating systems, or microservices.
WOAH! What?!
OK! Let me explain this to you in easy words. Suppose you are in a restaurant and you are dying to have that chocolate cake. You don't go straight to the chef for placing the order, right? The waiter does that for you. That's what API is. It's an interface that communicates between applications.
Here,
- You/Customer: Client
- Waiter: API
- Chef: Server Hence, in order to get the data from the web servers, we need APIs.
Let's call this API with
In our example, we are using FunTranslationAPI to fetch the data in JSON format(key - value pair).
Let's call the API then!
Fetch API
The Fetch API is a modern interface that allows you to make HTTP requests to servers from web browsers to given URL.
Basic syntax involved:
fetch(url)
.then(response => {
// handle the response
})
.then(data => console.log(data))
.catch(error => {
// handle the error
});
Here in the fetch()
function we pass the URL of the resource from where we are requesting the data. This will pass the data as a response
object. The response
object is the API wrapper for the fetched resource with a number of useful properties and methods to inspect the response. This will then passed to the data
variable (you can give any name to this) for printing output.
Now, it's time to define the functions.
Defining Functions() for some action
To get our code into some action, we need to define some functions.
function translateFunction(event){
var inputValue = inputElement.value; //fetching input value
fetch(url) //Fetch API call
.then(response => response.json())
.then(data => {
outputElement.innerText = data;
})
.catch(() => alert("Something wrong with the server! Try after sometime"))
Now, let's break it down:
- We'll extract
inputElement
value intoinputValue
variable. - Making
fetch
API call using the givenurl
and then extractingresponse
object. This is just an HTTP response, not the actual JSON. To extract the JSON body content from the response, we use thejson()
method via using an arrow function. - Setting
data
variable's value to theoutputElement
variable. - Finally, error handling with
catch()
function.
Let's try our application. Go to the browser, input your text & click on the translate button. You'll get the following output.
In console
{
"error": {
"code": 400,
"message": "Bad Request: text is missing."
}
}
That's not the output that we were expecting. That's because we've to pass the text to our URL. For that we'll define another function translatedURL()
.
function translatedURL(inputValue){
return `${url} ?text= ${inputValue}`;
}
Let's try our app with sample text Hi. How are you? and calling in fetch() function as fetch(translatedURL(inputValue))
instead of previous fetch(url)
to concatenate the text message to our server API's URL. We'll get output like this:
{
"success": {
"total": 1
},
"contents": {
"translated": "Good morrow. How art thee?",
"text": "Hi. How are you?",
"translation": "shakespeare"
}
}
Success! Not so much. Notice that the output text doesn't look pretty. This output is JSON data and we need to extract the translated value from it.
Here,
- translated: translated text
- text: input text
- translation: language of translation being used from FunTranslation API
We refer it by
json.contents.translated
. Now our code should look something like this:
function translatedURL(inputValue){
return `${url} ?text= ${inputValue}`;
}
function translateFunction(event){
let inputValue = inputElement.value;
let finalURL = translatedURL(inputValue);
fetch(finalURL)
.then(response => response.json())
.then(json => {
outputElement.innerText = json.contents.translated;
})
.catch(() => alert("Something wrong with the server! Try after sometime"))
}
and we get the following output:
Voila! We've built our very own Shakespeare Translation Web App with JavaScript Fetch API.
Note: Funtranslation APIs are free to use, hence they have a limitation of 5 calls/hour. Once it exceeds this limit, it would result in a failure with an error we've mentioned in the
catch()
block.
Finished for now...
Congrats on making it this far! We've got the basic understanding of DOM scripting i.e. JS in the browser, calling servers, and getting data from there, taking user input and showing user output, and many more things.
Now all that's left for you is to design your own styling with CSS. You can also check out funtranslation site for a similar app with different translation languages.
Click here to check out the live project.
Give it a try, create your version of the same and share your experience and feedback on the comments section.
Thanks for reading!
This content originally appeared on DEV Community and was authored by Neha Gupta
Neha Gupta | Sciencx (2021-04-10T20:50:54+00:00) Build your own Shakespeare Translation Web App with JavaScript Fetch API. Retrieved from https://www.scien.cx/2021/04/10/build-your-own-shakespeare-translation-web-app-with-javascript-fetch-api/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.