How to Translate languages on Websites with JavaScript

How to Translate languages on Websites with JavaScript

Language translation using JavaScript. We can achieve this using the Google Transliteration API

Introduction

In this post, we are going to discuss how to translate languages on websites. Sometimes we need to save data in local languages instead of English. In cases such as these, we need to give an option for the user to type in local languages. We can achieve this using the Google Transliteration API.

First, create an HTML file, then write the code shown below

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0  
Transitional//EN">  
<HTML xmlns:o>  
<HEAD>  
<TITLE>  
 language transliteration  
</TITLE>  
<script type="text/javascript" src="http://www.google.com/jsapi"></script>  
<script type="text/javascript">  
google.load("elements",  
"1", {  
 packages:  
       "transliteration"  
     });  
function onLoad() {  
var options =  
 {  
  sourceLanguage:  
  google.elements.transliteration.LanguageCode.ENGLISH,  
  destinationLanguage:  
  google.elements.transliteration.LanguageCode.KANNADA,  
  shortcutKey:  
   'ctrl+g',  
   transliterationEnabled:  
    true  
  };  
 var  
control =  
new  
google.elements.transliteration.TransliterationControl(options);  
control.makeTransliteratable(['transliterateTextarea']);  
}  
google.setOnLoadCallback(onLoad);  
</script>  
</HEAD>  
<BODY>  
<div class="base" align="center">  
<TABLE class="standard"  width="1200">  
<TBODY>  
<TR>  
<TD class="mainPanel">  
<TABLE>  
<TBODY>  
<TR>  
<TD vAlign="top"width="800">  
<TABLE cellPadding="5">  
<TBODY>  
<TR>  
<TD>  
<form name="convarea" action="" ID="Form1">  
 <table ID="Table2">  
 <tr>  
 <td align="center">  
<textarea id="transliterateTextarea" style="width: 550px; height: 220px" name="DraftxData"></textarea>  
</td>  
</tr>  
 <tr>  
 <td style="color:Gray">  
(Press  
Ctrl+g to toggle between English and  
kannada)  
</td>  
</tr>  
</table>  
 </form>  
 </div>  
</BODY>  
</HTML>    

Please run your HTML file in a browser and in the text area, type something in your destination translation language. In this example, my target translation language is "Kannada." Therefore, I will type "Hello C# Corner" and it will reflect in the Kannada language. Please check the below snapshot

Let's try with the Hindi language. To do this we need to set the destination translation langauge as Hindi. Please check the below code snippet that I am changing

function onLoad() {    
var options =    
 {    
  sourceLanguage:    
  google.elements.transliteration.LanguageCode.ENGLISH,    
  destinationLanguage:    
  google.elements.transliteration.LanguageCode.HINDI,    
  shortcutKey:    
   'ctrl+g',    
   transliterationEnabled:    
    true    
  };    

After saving the above changes, please run your HTML file and type "Hello C# Corner." It will be translated in Hindi. Please check the below snapshot

You can now enable Indian language typing in websites. It will support all major Indian regional languages.

Summary

We discussed how to enable Indian language typing on websites. I hope it's helpful.

Thank you for reading!

JavaScript Tutorial: if-else Statement in JavaScript

JavaScript Tutorial: if-else Statement in JavaScript

This JavaScript tutorial is a step by step guide on JavaScript If Else Statements. Learn how to use If Else in javascript and also JavaScript If Else Statements. if-else Statement in JavaScript. JavaScript's conditional statements: if; if-else; nested-if; if-else-if. These statements allow you to control the flow of your program's execution based upon conditions known only during run time.

Decision Making in programming is similar to decision making in real life. In programming also we face some situations where we want a certain block of code to be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program.

JavaScript’s conditional statements:

  • if
  • if-else
  • nested-if
  • if-else-if

These statements allow you to control the flow of your program’s execution based upon conditions known only during run time.

  • if: if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
    Syntax:
if(condition) 
{
   // Statements to execute if
   // condition is true
}

Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it will execute the block of statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider the immediate one statement to be inside its block. For example,

if(condition)
   statement1;
   statement2;

// Here if the condition is true, if block 
// will consider only statement1 to be inside 
// its block.

Flow chart:

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If statement 

var i = 10; 

if (i > 15) 
document.write("10 is less than 15"); 

// This statement will be executed 
// as if considers one statement by default 
document.write("I am Not in if"); 

< /script> 

Output:

I am Not in if
  • if-else: The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.
    Syntax:
if (condition)
{
    // Executes this block if
    // condition is true
}
else
{
    // Executes this block if
    // condition is false
}


Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If-else statement 

var i = 10; 

if (i < 15) 
document.write("10 is less than 15"); 
else
document.write("I am Not in if"); 

< /script> 

Output:

i is smaller than 15
  • nested-if A nested if is an if statement that is the target of another if or else. Nested if statements means an if statement inside an if statement. Yes, JavaScript allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.
    Syntax:
if (condition1) 
{
   // Executes when condition1 is true
   if (condition2) 
   {
      // Executes when condition2 is true
   }
}

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate nested-if statement 

var i = 10; 

if (i == 10) { 

// First if statement 
if (i < 15) 
	document.write("i is smaller than 15"); 

// Nested - if statement 
// Will only be executed if statement above 
// it is true 
if (i < 12) 
	document.write("i is smaller than 12 too"); 
else
	document.write("i is greater than 15"); 
} 
< /script> 

Output:

i is smaller than 15
i is smaller than 12 too
  • if-else-if ladder Here, a user can decide among multiple options.The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
if (condition)
    statement;
else if (condition)
    statement;
.
.
else
    statement;


Example:

<script type = "text/javaScript"> 
// JavaScript program to illustrate nested-if statement 

var i = 20; 

if (i == 10) 
document.wrte("i is 10"); 
else if (i == 15) 
document.wrte("i is 15"); 
else if (i == 20) 
document.wrte("i is 20"); 
else
document.wrte("i is not present"); 
< /script> 

Output:

i is 20

Learn JavaScript Crash Course | Best Javascript Tutorial

Learn JavaScript Crash Course | Best Javascript Tutorial

Take the first steps to mastering JavaScript, one of the fastest growing languages globally today. Because of its flexibility, it is there everywhere today: be it the web, mobile and or the desktop. Want to be one of the over 50,000 people who have benefited from this course? Join the learning fun!

Description
So you need to learn Javascript and learn it fast!

Are you a designer who's now adding JavaScript to your knowledge arsenal? Are you a student who needs a fast and high-quality JavaScript course? Are you a traditional developer trying to learn the basics? Are you applying for a job that requires JavaScript.

JavaScript is not only emerging as the most important language to know, it's flexibility is unique. With JavaScript being deployed on the web, mobile and even the desktop this is the one language that all technologists need to know. As a JavaScript developer you'll find opportunity around every corner!

This is a crash course meaning it moves quick. Every meaningful lecture is chock full of information that you can immediately apply to your coding work. Taught by a master instructor, you'll find that Javascript: Crash Course is a extremely efficient way to learn.

Each lecture course lecture includes the actual code developed by the master instructor during the lecture. No more staring at a blank screen when figuring out how to practice use the included code as a starting point.

The course culminates with developing a full quiz application called Trivia. You'll learn from building out this application yourself and modifying it and making it your own!

Join the over 500,000 learners who've enjoyed LearnToProgram courses. At LearnToProgram, we're teaching the world to code!

Who is the target audience?

Newbies Who Want to Learn Javascript Quickly
Current Programmers who need a Crash Course in Javascript
Those with Limited Time who Want to Learn Alot
Teacher and Students
Designers and Developers who Want to Learn JavaScript Efficiently
Basic knowledge
Foundational HTML
Text editor
Web Browser
What will you learn
Understand and write Javascript Code
Run Javascript Code in a Browser
Choose and Utilize Tools Used by Professional Javascript Developers
Understand the Purpose of Javascript Variables
Declare and Initialize Javascript Variables
User Variables with Strings and Numbers
Perform Mathematical Operations with Javascript
Obtain input from the User via Alert Boxes
Obtain input from the User via Forms
Understand Simple Conditionals with If
Create Complex Conditionals with If Else If
Create While Loops
Create For Loops
Understand the Purpose and Power of Javascript Objects
Use Event Objects to Track Events that Occur
Use the Javscript Date Object to Track Dates
Use the Javascript String Object to Manipulate Strings
Include Audio and Video Content with the Media API
Use the XMLHttpRequest() Object to Exchange Data
Create a Basic Ajax Request
Parse JSON code

How to Send Emails From Javascript

How to Send Emails From Javascript

Sending an email through your web app is some times a hectic process for beginners. In this article, I will walk you through a simple JavaScript task assignment app.

Sending an email through your web app is some times a hectic process for beginners. In this article, I will walk you through a simple JavaScript task assignment app. The user can add the assignee name, email and task description and can simply send email to the assignee with task details using a library called email.js. I will also explain how you can persist the task using local storage.

Prerequisites

In order to follow the article, you should be familiar with HTML, Bootstrap and JavaScript. You can use any code editor to follow along.

Learning outcomes
  • JavaScript DOM Traversal
  • Using JavaScript Library
  • Local Storage
Final Look of the app

Bootstrap 4 cdn

I will be using Bootstrap 4’s CDN for the app. You can either use it or may use some other way to add it to your app.

 <!-- Add this in <head> element-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<!-- Add this before closing body tag -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> 
Developing app’s front-end

Create a file named index.html and add the following piece of code.

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Required meta tags always come first -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <title>JS Email</title>
</head>

<body>
    <header class="jumbotron">
        <div class="container">
            <div class="row">
                <div class="col-12 col-sm-12 text-center">
                    <h1>Send Email through JavaScript</h1>
                </div>
            </div>
        </div>
    </header>
    <div class="container-fluid">
        <div class="row">
            <div class="col col-sm"></div>
            <div class="col-sm-6 col-12">
                <label for="task">Task Description: </label>
                <input type="text" id="task" class="form-control" required>
                <div class="row">
                    <div class="col-sm-6 col-12">
                        <label for="assigneeName">Assignee Name: </label>
                        <input type="text" id="assigneeName" class="form-control" required>
                    </div>
                    <div class="col-sm-6 col-12">
                        <label for="assigneeEmail">Assignee Email:</label>
                        <input type="email" id="assigneeEmail" class="form-control" required>
                    </div>
                </div>

                <label for="dueDate">Due Date: </label>
                <input type="date" id="dueDate" class="form-control" required>
                <button type="button" class="btn btn-success mt-1">Add Task</button>
            </div>
            <div class="col col-sm"></div>
        </div>
        <hr>
        <div class="row">

        </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> 
</body>

</html>

The above given code snippet setups the layout of the app. Now let us add the functionality. After filling the required information, when the user clicks on the Add Task button, the task should be added to the DOM (Document Object Model) as a Bootstrap card. For this purpose, let’s write JavaScript code first.

Adding JavaScript

Let’s add the JavaScript to bring life to the app. Create a file named app.js and add the code given below.

//add button
const addBtn = document.querySelector('button');
//the row where cards will be appended
const taskDiv = document.querySelectorAll('div.row')[3];
//Retrieve from Local Storage 
taskDiv.innerHTML = localStorage.getItem('tasks');
//task description input element
const taskDescription = document.querySelector('#task');
//assignee name input element 
const assigneeName = document.querySelector('#assigneeName');
//assignee emal input element
const assigneEmail = document.querySelector('#assigneeEmail');
//due date input element
const dueDate = document.querySelector('#dueDate');

//Click listener for add button
addBtn.addEventListener('click', () => {
    //Create a new div
    let div = document.createElement('div');
    //Add class to div
    div.className = 'col-12 col-sm-4 mt-1';
    //Create a div for bootstrap card
    let card = document.createElement('div');
    //Add card class
    card.className = 'card';
    //Create card head
    let cardHead = document.createElement('div');
    //add card header class 
    cardHead.className = 'card-header';
    //create card body
    let cardBody = document.createElement('div');
    cardBody.className = 'card-body';
    //create card footer
    let cardFoot = document.createElement('div');
    cardFoot.className = 'card-footer';
    //Append the card components to the card div
    card.appendChild(cardHead);
    card.appendChild(cardBody);
    card.appendChild(cardFoot);
    //Create h2 Element for assignee name display
    let name = document.createElement('h2');
    //get value from name input field
    name.className = 'name';
    //due date element
    let datee = document.createElement('h3');
    //get value from date input field
    datee = dueDate.value;
    //Set assignee name and date
    name.innerHTML = assigneeName.value + '<small class="text-danger pl-1">Due: ' + datee + '</small>';
    cardHead.appendChild(name);
    //Create element for p which is task description
    let desc = document.createElement('p');
    desc.textContent = taskDescription.value;
    //Append the description to card body element
    cardBody.appendChild(desc);
    //Create a button for card to send email
    let sendBtn = document.createElement('button');
    sendBtn.className = 'btn btn-info';
    sendBtn.textContent = 'Send Mail';
    //Assign the data-email attribute to store the email value
    sendBtn.setAttribute('data-email', assigneEmail.value);
    cardFoot.appendChild(sendBtn);
    div.appendChild(card);
    taskDiv.appendChild(div);
    //store to local storage
    localStorage.setItem('tasks', taskDiv.innerHTML);
});
});

The above piece of code is doing the following things:

  • It gets the values from the input fields.
  • A click listener is written for click event of Add Task button.
  • The click listener dynamically adds the new task card.
Setting Up the emailjs account for sending email

Sign up for the account here.

Add the Personal Email Gmail as service and Connect your account.

Provide the required details

Click on the Email Templates tab and Add New Template with name Task.

Set the email template as shown in the figure below:

Click on the Installation option as shown in the picture below and add the code snippet to **** of your index.html file.

Also add the app.js file to your index.html file before the closing tag of body.

Now, in your app.js file, add the following piece of code:

taskDiv.addEventListener('click', function() {
    if (event.target.tagName == 'BUTTON') {
        let p = event.target.parentElement.parentElement;
        let n = p.firstElementChild.textContent;
        let nm = (n.substr(0, n.indexOf("Due:")));
        let t = p.children[1].firstElementChild.textContent;
        console.log(t);
        var templateParams = {
            email: event.target.getAttribute('data-email'),
            name: nm,
            task: t
        };
        emailjs.send('default_service', 'task', templateParams);
    }
});

The above given code sets the email parameters to be sent.

This is how your index.html and app.js file will look like:

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Required meta tags always come first -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script type="text/javascript">
        (function() {
            emailjs.init("YOUR USER ID");
        })();
    </script>
    <title>JS Email</title>
</head>

<body>
    <header class="jumbotron">
        <div class="container">
            <div class="row">
                <div class="col-12 col-sm-12 text-center">
                    <h1>Send Email through JavaScript</h1>
                </div>
            </div>
        </div>
    </header>
    <div class="container-fluid">
        <div class="row">
            <div class="col col-sm"></div>
            <div class="col-sm-6 col-12">
                <label for="task">Task Description: </label>
                <input type="text" id="task" class="form-control" required>
                <div class="row">
                    <div class="col-sm-6 col-12">
                        <label for="assigneeName">Assignee Name: </label>
                        <input type="text" id="assigneeName" class="form-control" required>
                    </div>
                    <div class="col-sm-6 col-12">
                        <label for="assigneeEmail">Assignee Email:</label>
                        <input type="email" id="assigneeEmail" class="form-control" required>
                    </div>
                </div>

                <label for="dueDate">Due Date: </label>
                <input type="date" id="dueDate" class="form-control" required>
                <button type="button" class="btn btn-success mt-1">Add Task</button>
            </div>
            <div class="col col-sm"></div>
        </div>
        <hr>
        <div class="row">

        </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js">
</script> 
    <script src = "app.js"></script>
</body>
</html>

app.js

//add button
const addBtn = document.querySelector('button');
//the row where cards will be appended
const taskDiv = document.querySelectorAll('div.row')[3];
//Retrieve from Local Storage 
taskDiv.innerHTML = localStorage.getItem('tasks');
//task description input element
const taskDescription = document.querySelector('#task');
//assignee name input element 
const assigneeName = document.querySelector('#assigneeName');
//assignee emal input element
const assigneEmail = document.querySelector('#assigneeEmail');
//due date input element
const dueDate = document.querySelector('#dueDate');

//Click listener for add button
addBtn.addEventListener('click', () => {
    //Create a new div
    let div = document.createElement('div');
    //Add class to div
    div.className = 'col-12 col-sm-4 mt-1';
    //Create a div for bootstrap card
    let card = document.createElement('div');
    //Add card class
    card.className = 'card';
    //Create card head
    let cardHead = document.createElement('div');
    //add card header class 
    cardHead.className = 'card-header';
    //create card body
    let cardBody = document.createElement('div');
    cardBody.className = 'card-body';
    //create card footer
    let cardFoot = document.createElement('div');
    cardFoot.className = 'card-footer';
    //Append the card components to the card div
    card.appendChild(cardHead);
    card.appendChild(cardBody);
    card.appendChild(cardFoot);
    //Create h2 Element for assignee name display
    let name = document.createElement('h2');
    //get value from name input field
    name.className = 'name';
    //due date element
    let datee = document.createElement('h3');
    //get value from date input field
    datee = dueDate.value;
    //Set assignee name and date
    name.innerHTML = assigneeName.value + '<small class="text-danger pl-1">Due: ' + datee + '</small>';
    cardHead.appendChild(name);
    //Create element for p which is task description
    let desc = document.createElement('p');
    desc.textContent = taskDescription.value;
    //Append the description to card body element
    cardBody.appendChild(desc);
    //Create a button for card to send email
    let sendBtn = document.createElement('button');
    sendBtn.className = 'btn btn-info';
    sendBtn.textContent = 'Send Mail';
    //Assign the data-email attribute to store the email value
    sendBtn.setAttribute('data-email', assigneEmail.value);
    cardFoot.appendChild(sendBtn);
    div.appendChild(card);
    taskDiv.appendChild(div);
    //store to local storage
    localStorage.setItem('tasks', taskDiv.innerHTML);
});

taskDiv.addEventListener('click', function() {
    if (event.target.tagName == 'BUTTON') {
        let p = event.target.parentElement.parentElement;
        let n = p.firstElementChild.textContent;
        let nm = (n.substr(0, n.indexOf("Due:")));
        let t = p.children[1].firstElementChild.textContent;
        console.log(t);
        var templateParams = {
            email: event.target.getAttribute('data-email'),
            name: nm,
            task: t
        };
        emailjs.send('default_service', 'task', templateParams);
    }
});

Create a new task and add the task. Like the following:

Click on Send Mail and the email will be sent to the user with the task details.

Thank you for reading, please comment if you have any question.