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.