Saturday, December 17, 2016

Multi language file by using javascript

Why we need the language file in application/software/website?

There are many reasons to use the different language files in an application. One main reason is to make a great user-interface application. The user is more comfortable and satisfied when she would be able to use any software/website along with her first language.

Language plays a vital role to make the connection between user and software. It’s critical to have the multi-language facility in software for it succeeds.

Today I am going to write about how to make the multi-language feature in JavaScript.

How do I create this?

I create the function which loads the language file as a javascript object which has key and value. The key is used to fetch its associated string/information.

I create another function getString, to which we can pass the key for getting its related string from language object like lang.getString(‘greeting’).

The user can also pass the dynamic values with lang.getSting(‘greeting’, [overridevalue] ) to make the string more informative. I have explained this point in detail at below.

Live Demo

Find the demo with and

Let’s understand the complete process with the code.

Load language file by script

var lang = {
/**
 function load the language file passed by function
**/
init : function (type, afterLoad){
 this.type = type;
 var stag = document.createElement("script");
 stag.type = 'text/javascript';
 stag.src = type+".js";
 document.querySelector("head").appendChild(stag);
 stag.onload = function (){
  afterLoad();
 }
},

In above code, I have defined the module named lang, in which the init function loads a language file by passing file name eg en, fr, pt during initialize the module.

The callback function afterLoad would be invoked when the file is loaded, which means you can use the language object only after the file is loaded.

Get the language string by passing key
/**
 This function is used to get string in your language
 passed by relative keyword
**/
getString : function (string, words){
 if(typeof window[this.type] != 'undefined'){
  var langString = window[this.type][string];
  if (typeof words != 'undefined' && words.length > 0) {
   langString = this.putDyanamicValue(langString, words);
  }
  return langString;
 }else {
  alert("'" + this.type +  '" language is not found');
 }
},
getString is the core function, it returns the language string based on the key you provided. For example, if language file has “greeting” : “Hello User”, then the getString(“greeting”) returns “Hello User".

Insert the dynamic values in String

/**
 This puts the dynamic values in string passed by function, 
 eg dynamic value DVD  
 "Your Item {dvalue1} is not found"  is converted into
  "Your Item DVD is not found"
**/
putDyanamicValue : function (langString, words){
 for (var i = 0; i < words.length; i++) {
  var spatt = new RegExp('{dvalue' + (i + 1) + '}');
  langString = langString.replace(spatt, words[i]);
 }
 return langString;
}
}

The above function overrides the dynamic values that is passed through getString function to prefixes, for example {dvalue1} and {dvalue2} in string. If the language file has

itemnotfound : “Your Item {dvalue1}
is not found", Select the item  {dvalue2} ”,

then the

getString(“itemnotfound ”, [“VCR”, “DVD”]);  returns  "Your Item VCR is not found, Select the item DVD”.

"VCR" and “DVD” would be replaced with  {dvalue1} and {dvalue2}.  As many as the dynamic values passed in an array, the number of prefixes should be defined with a particular string in a language file.
As an example, there are three elments in an array with lang.getString(somekey, [val1, val2, val3]),
and the same way, three prefixes would defined in string with somekey : I have {dvalue1},  {dvalue2} and  {dvalue3},


Create language file with javascript object

France language file fr.js
var fr = {
 greeting : "Bonjour l'utilisateur!",
 itemnotfound : "Cet élément {dvalue1} est introuvable. Veuillez sélectionner l'élément {dvalue2}"
}
English language file en.js
var en = {
 greeting : "Hello USER!",
 itemnotfound : "This item {dvalue1} is  not found. Please select the item {dvalue2} "
}
To initialize the language module
lang.init('en', afterLangLoad);
In above code, the ‘en’ is language file and afterLangLoad is a callback function wlil be triggered when the file is loaded. And finally you can use the language string as in below function.
function afterLangLoad(){
 var msg = lang.getString('greeting'); + " 
" msg += lang.getString('itemnotfound', ["VCR", "DVD"]); console.log(msg); }

You can get the jsFiddle and source code Here.

If you want to ask/share anything about article, you are welcome to drop this on below comment box.

Saturday, December 10, 2016

Progress bar is created by plain JavaScript

Today I am going to write about how you can create the Progress Bar by using Plain JavaScript. To create this, you just need some knowledge about HTML, CSS, and JavaScript.

How do I create this ?

We create two divs, one is a progress bar and other is its wrapper and the first div would exist inside the wrapper div. After that, we give the width, height, and background to parent div.
Now we apply the height and background color to inner progress bar div and 1px width for this div at very first.

Now we increase inner div’s width at given time of interval, suppose we increase this width by 1 pixel at 50 milliseconds.  So it gives us the progress bar effect.

For live Demo just



Let’s understand this with the code.


By above HTML code, I have just created the progress bar wrapper div.

I have achieved this tool by creating the JavaScript module named progressBar.

var progressBar = {
/** These are default values for progressbar **/
start : 0,
end : 100,
speed : 50,
style : { width : 300, height : 30, bgColor : "#616060", radius : 10, pbarColor : "#bb1414"}, 
callback : null,
elem : null,

In above code, I have just defined the module named progessBar and it defaults values which will be used if the module is invoked without providing its customized values.

Setting up the customize values

/** this function is setting up the customize values **/
init : function (elem, speed, start, end, style, callback) {
	if(elem == null){
		alert("Progress Bar Cotainer is missing, \nProvide the Progressbar Container.");
	} else {
		
		this.elem = elem || this.elem;
		this.speed = speed || this.speed;
		this.start = start || this.start;
		this.end = end || this.end;
		this.style = style || this.style;
		this.callback = callback || this.callback;
		
		var elem = document.querySelector(this.elem);
		if(elem != null){
			this.stylePbarParent(elem);
			this.createProgressbar(elem);
			this.calcStep();
			this.render();
		}else{
			alert('There is no an element for Progressbar.');
		}
	}
},

The init() is main function which should be invoked to use this module, something like progressBar.init(“#somelement”);.

This function does lots of stuff, like overrides the default values, creates elements, and renders the progress bar. We will understand this whole by knowing following functions

Set various dimensions to parent div

/**
	Set the styles for parent element of progressbar
**/
stylePbarParent : function (elem){
	elem.style.width = this.style.width + "px"; 
	elem.style.backgroundColor = this.style.bgColor; 
	elem.style.height = this.style.height + "px";
	elem.style.borderRadius = this.style.radius + "px"; 
},
The above function stylePbarParent sets the various dimensions like width, height, background, etc to parent div of the progress bar.

Create inner progress bar div

/** 
	this function creates main progressbar element 
*/
createProgressbar : function (parentElem){
	this.pbarElemId = 'progressbar';		
	var elem = document.createElement('div');
	elem.id = this.pbarElemId;
	elem.style.backgroundColor  = this.style.pbarColor;
	elem.style.height  = parentElem.style.height;
	elem.style.borderRadius = (this.style.radius-2) + "px"; 
	parentElem.appendChild(elem);
},

In above function createProgressbar, I have created the element with various attributes, this element will act like progress bar after the animation is started.

Calculate the width for inner div

	
/**remove the numbers after two decimal **/
remmoveDecimal : function (number){
	return (Math.floor(number * 100) / 100);
},

/**
 This calculates the step like, if progressbar width is
 500, the each step would be 5
**/
calcStep : function (){
	var width = (this.style.width / 100);
	this.step  = this.remmoveDecimal(width); // retain only two decimal points
	this.currWidth = this.start == 0  ? this.step :  this.remmoveDecimal((this.step * this.start));
},

With above two functions remmoveDecimal and calcStep, I am getting the width which would be applied to inner div at each iteration of animation.

Render the progress bar

	
/**
	This function renders the actual progressbar by increasing
	it's width, the progressbar will be ended after reached in maximum level 
**/
render : function (){
	var elem = document.querySelector('#' + this.pbarElemId);
	elem.style.width = this.currWidth + "px";
	
	if(this.start >= this.end){
		if(this.callback != null){
			// if callback bassed, it will be invoke on progressbar finished
			this.callback(); 
		}
	}else {
		var fps = 1000 / this.speed;
		var that = this;
		this.renderPbr = setTimeout(
			function (){
			   // Increase performance by
			   // Only perform animation, when browser is able to perform,
			   // It does not execute when browser tab is inactive
			   requestAnimationFrame(function (){that.render();})
			   that.start++;
			   that.currWidth += that.step;
			}, 1000/fps
		);
	} 
}
};

render() is a very important function which does animation, it basically increases the width of inner div at a given time of interval. The animation will be stopped when the start point is meet the end point, in simple words, it's stopped when the progress bar is completed.
If their callback is given when the module is initialized, will be invoked by this.callback(); in the completion of the progress bar.
For invoking the module you could do something like

progressBar.init("#progressbarCont", 50, 0, 100, { width : 500, height : 40, bgColor : "black", radius : 10, pbarColor : "red"}); 


You can find the complete code from HERE.

Sunday, December 4, 2016

How to test Internet Bandwidth by JavaScript

Today, I am going to write about how to measure the bandwidth speed by using JavaScript. It might be unreliable few times, but usually, it gives the basic idea that how much bandwidth/internet speed you have.

Our JavaScript is going to download the image from the internet to calculate the speed, let's see how it’s measured.

We mark the time when image-downloading is started and the time when that image is downloaded. Then we calculate the bandwidth speed by getting the differences between the times(downloadEndTime - downloadStartTime).

Let’s understand along with the code,


this.downloadSize : 1500000;  // Total size of image is 1.5 MB
var myImage = new Image();
this.startTime = (new Date()).getTime();
 // Everytime this method is invoked, the image is downloaded from Server not from Cache
var cacheBuster = "?nnn=" + this.startTime;
myImage.src = "https://raw.githubusercontent.com/sumanbogati/images/master/jstutorial/bandwidth-test.jpg" + cacheBuster;
In above code, we get the time when an image is starting to download by

this.startTime = (new Date()).getTime();
The remaining code is used to download the image, I'll describe the usage of cacheBuster towards the end of this article.
Following myImage.onload method will be invoked after an image is downloaded and that.endTime contains the time of this event.

var that = this;
myImage.onload = function () {
	that.endTime = (new Date()).getTime();
	var speedKbps = that.calculate();
}
We have 'start' and 'end' time of image-downloading process with this.startTime, and this.endTime, now the calculate method measures the speed based on these times,
calculate : function (){
	var duration = (this.endTime - this.startTime) / 1000;
	var bitsLoaded = this.downloadSize * 8;
	var speedBps = (bitsLoaded / duration).toFixed(2);
	var speedKbps = (speedBps / 1024).toFixed(2);
	return Math.round(speedKbps);
}
In above function, bitsLoaded demonstrates the total downloadable size of an image in bits. Now, we calculate the speed in bytes per second by (bitsLoaded / duration), finally we get the speed in Kbps through speedBps/1024.
Points are worth to notice:-

I applied the cacheBuster concept in above code, this technique forces the browser to a fresh download of an image from the Internet instead of Cache.
I used the jpeg image format for this tutorial because the server/internet is not able to compress this image type, so the image would be downloadable to its original size.

Live Demo

Bandwdith speed is :-




You can get the source code HERE.

Saturday, November 26, 2016

What requestAnimationFrame is ?

Animation with traditional way

For creating animation with JavaScript, we use setInterval() and setTimeout(). These functions execute the passed function at given time. And with setInterval, there would execute the function after each given time interval. The following example does console the message after every second.

function draw(){
 console.log(“draw something  after every second”);
}
setInterval( draw, 1000 );

Disadvantages of setInterval/setTimeout

So what are the disadvantages of setInterval/setTimeout. It does not care what is going on CPU/ Browser, enough resource is available or not, if there is low or high battery and if a user is in current tab of browser or in another tab. This stuff is not considered by setInterval/setTimeout.

It goes for executing the assigned task at given time of interval, It does not respect CPU resources, browser’s workload etc. These are the reasons, complex setInterval can cause the problem while other application uses the extensive CPU.  As a result, the browser would be unresponsive or crashed.

To overcome the problem

So get rid of all these issues, we can use requestAnimationFrame function. This API is created by people of Mozilla and adopted by other browser vendors, later.

So it’s basically used to create animation with JavaScript, let’s explore how does this work.

function draw() {
 console.log('Your draw code is executed here..');
 requestAnimationFrame(draw);
}
draw();
The draw method displays the message in a console of your browser. We execute this function by invoking draw();. Inside the draw function, after display the message, new draw() is  invoked by requestAnimationFrame(draw). The requestAnimationFrame does not invoke the draw method unless the browser is ready.  

Above script displays the message with 60 frames per second.  Short description about frame rate is mentioned at last of this article.

What if there is a need of less than 60fps

The below code is same like above(requestAnimationFrame) along the disadvantages of setInterval/setTimeout

setInterval(
 function (){
  console.log('Your draw code is executed here..');
 }, (1000/60)
);

If someone wants the frame rate less than 60, what to do? Not to worry, here is the solution. For example, if you want the 16fps by requestAnimationFrame. You could do something like this.

var fps = 16;
function draw() {
 setTimeout(
  function (){
   console.log('Your draw code is executed here..');
   requestAnimationFrame(draw);
  }, (1000/fps)
 );
}


In this code, we use the setTimeout function inside draw method to achieve the 16 frame rate per second.

There are great benefits of using requestAnimation, it asks the browser if there is the possibility of drawing of next frame, It draws only if possible otherwise it ignores.

Suppose you are using setInterval/setTimeout in your page, now you go to another tab in your browser. Chrome/firefox throttles the animation speed by 1 frame per second. However, it does not stop completely.

Traditional vs New way

If you create the same animation by requestAnimationFrame, then the animation task would be stopped and there are no expenses of CPU for this task while you are in another tab. Less CPU means a long battery for your laptop and mobile.

You can see the two different screenshots, first, is using by setInterval and second is using by requestAnimationFrame

animation with a traditional way


animation with requestAnimationFrame way

You can get the complete example over here. To see the difference, switch the tab after rendering these examples in browser

Frame Rate
By default, there is 60fps rate in  requestionAnimationFrame. With javascript, the frame rate is the rate, on which browser draws screen 60 times per second. In normal, the movie would play with 30fps, which means in one second, there are 30 pictures are summed together and presented like the movie.

Saturday, November 19, 2016

Web worker for separate thread in JavaScript

What Web worker is ?


JavaScript is a single-threaded programming language. It would be executed in a single thread only, this is the reason when you use heavy JavaScript code for your application, the UI of application would be blocked because the heavy script uses all CPU with main/single thread.


In a single thread, all the script is executed one by one, If the particular code uses the extensive CPU which means other code can not be executed meanwhile.

As a result, JavaScript application is not able to give the response to user interaction, so It’s pretty bad experience to end user.

Web-worker shines over here, what basically it does is, provide the facility of multi-threading for JavaScript application. So the application can use the heavy code in another thread by using web worker and make free the main thread to respond the user input.


For example, if you run large loop in your JavaScript code, which uses 95% CPU, now suppose user click on a button for any task, then user interface in the browser is not responded, in this case, we can place that heavy code in worker as a separate thread.

So that ”95% CPU consuming code” would be executed in the background with a different thread, and the main thread is available for User Interface.

How to use Web Worker ?

To add the web worker on your page, you could do something like.

 var anyWorker  = new Worker('anyJsFile.js'); 

anyJsFile.js is worker file treated as separate thread, now the worker object is available with anyWorker object,

By using postMessage() method with worker object we can send the data to worker, like

Main.js
// the data should be in object format
var car = {
  model : 'GLA-200',
 color : 'White',
 price : null
}
// the data would pass to the worker
anyWorker.postMessage(car); 
This above code sends the car object to the worker.

This car object can be found at worker file by doing something like
anyJsFile.js
onmessage = function (e){
 var wCar = e.data;
 wCar.price = '$70000';
 wCar.company = 'Mercidies Benz';
 postMessage(wCar);
}
After modified the car object you can pass the modified object by postMessage(wCar) method  to main thread(main.js)

By the following code, you can get that modified data as e.data on main thread with onmessage method

anyWorker.onmessage = function (e){
 // get modified object from worker
 var mcar = e.data; 
 console.log(
 'Car model is ' + mcar.model + '\n' + 
 'Car color is ' + mcar.color + '\n' + 
 'Car price is ' + mcar.price + '\n' + 
 'Car company is ' + mcar.company + '\n' 
 );
}


The below points are worth to read

Same Origin Policy

The worker file and the code for an attempt to using that worker should be placed in same origin policy. Like anyWorker.js and main.js file should be located under same domain like http://javascriptfuture.com

DOM/BOM

The BOM(browser object model) and DOM(document object model) are not available for the web worker.

You can find the working example with Web-worker.


Sunday, April 3, 2016

How to build/compile from phonegap app to android app by using android sdk and phonegap cli?

This article lights the information about build Phonegap app to android App (someApp.apk).

Tools Required

You need to install the below tools, this article is not about how to install these tools. You will get
various information on the internet about installing process.

1) nodejs
2) Git

After installing this, run below command for installing latest phonegap cli

npm install -g phonegap@latest

Now install the Android SDK ide from Here.

Add environment variable

Create new environment path variable ANDROID_HOME and add your Android sdk path as shown in below image. My android sdk location is as mentioned below, it might differ in your case.

C:\Users\suman\AppData\Local\Android\sdk


Add the below line in PATH variable, follow the instruction as shown in below image

;%ANDROID_HOME%\platform-tools;%ANDROID_HOME%\tools;


Be careful, do not remove any other path when you would add ANDROID_HOME path variable.

Chek Android Sdk is installed

Now run the command android from your “command prompt”, below screen ensures that the android sdk is installed.


Now you have installed all required tools nodejs, git, phonegap cli, and android sdk. Now it's time to create and build a phonegap project.

Create phonegap Project

Make a phonegap project by running

phonegap create hello com.myapp.hello HelloWorld

Customize the app

Now, do customize your app as your requirement. After done this go to project directory by

cd hello

From your project folder, Add the platform for your app according to your requirement, it's Android in my case, so I initiate the command

phonegap platform add android

Now, import that created project hello in your Android Sdk IDE, for doing this open the android sdk and do click on link Import project (Eclipse ADT, Gradle etc) as in



After importing the project, select "Project Files" like


From here also you may able to customize the app as shown in below image



Build/Compile phonegap app to Android app

For compiling the app with your Android Sdk IDE, go to "Build -> Generate Signed APK",  and create the key for your app by providing required information as indicated by below image.


During the build process you can change the app file name as in my case it's myappname.apk,


Move on as suggested by and Android Sdk IDE, After a while, the build process will be completed and the window is opened as below



Now the app mappname.apk is ready to install in your android phone.