Archive for the Category ◊ Javascript ◊

Friday, May 17th, 2013

I: “I have a simple requirement to be accomplished using Javascript. Can you help me on this?”
You: “Not Again !!!!”
I: “Write a function to return sum of two number passed as arguments”
[By the time I finish reading the requirement you will have the below code]
You: “Here you go !” [With a teasing smile and a dirty look at me ]

function add(x,y)
{
return x + y;
}

Now, the usual thing : Requirement Changes :P
I: “Instead of two parameters I want to pass 10 values as parameters and get the sum of the values. Can you do this?”
You: “You are wasting my time, but still I can do this simple task”
[After thinking for a while you start rewriting the function by adding 10 parameters....I wait and watch and by the time you complete adding 9th parameter...]
I: “Oops ! Requirement changes again, now I need the function to work for 50 parameters..”
You: “Get Lost ! I am not doing this”
I: “Let increase the complexity and add 50 more…and more…and more…”
You:!!!!????

Don’t worry! Dynamic Parameter Handling in Javascript will come for your help

Testing Javascript

/*
Function Name : addFunction
Parameters : Dynamically Passed during Invokation
Description : This Function is used to add the numbers passed as parameters
Input : param1,param2.....paramN
Output : This Function will display the Sum in alert box
*/
function addFunction()
{
var total = 0;
for (var i=0;i<addFunction.arguments.length;i++) //Retrieving the arguments passed
{
total += addFunction.arguments[i];
}
alert('Sum of numbers = ' + total);
}

/*
Function Name : callOnLoad
Parameters : N/A
Description : This Function is invoked on Page Load
Input : N/A
Output : This Function will inturn invoke addFunction();
*/
function callOnLoad()
{
addFunction(10,20,10,10); //Invoking Function with 4 Parameters
}

Category: Javascript  | Leave a Comment
Author:
Friday, January 18th, 2013

 

 

This tutorial will give you a basic idea about canvas, embedding & moving images inside canvas.

Situation/Requirement: Car runs & if it hit tree show bang. Car is controlled by 3 buttons, Start, Stop & Reverse.

I used 3 images

  1. Car
  2. Tree
  3. Bang

Game Plan

Program Starts:

HTML Code:

<canvas id="gameCanvas" width="800" height="400"></canvas>
<div style="margin-left:auto;margin-right:auto;width:800px;">
      <input type="button" id="startBtn" value="Start" />
      <input type="button" id="stopBtn" value="Stop" />
      <input type="button" id="reverseBtn" value="Reverse" />
</div>
  • Important tag is canvas, that acts as the container or screen where animation happens.
  • 3 buttons to perform actions.
<!—included jquery -->
<script type="text/javascript" src="javascript/jquery-1.9.0.min.js"></script>

<!—game.js contains the logic -->
<script type="text/javascript" src="javascript/game.js"></script>

Javascript (game.js):
Following are the global objects which are accessed throughout file.

//Global Objects
var gameCanvas; //Canvas Object
var gameContext; //Canvas Context
var carX = 0; //Car position
var carObj = new Image(); //Car Object
var animationObj; //Animation object or timer object

Major Functions:
Object creation of Canvas & Context for the created Canvas.

function getGameCanvasObject() {
   gameCanvas = document.getElementById("gameCanvas");
   gameContext = gameCanvas.getContext("2d");
}

Loads Car Image and draw in the position required inside the context.

function drawCar(pos) {
    carObj.onload = function() {
        gameContext.drawImage(carObj, pos, 280);
    };
    carObj.src = 'images/car.png';
}

Loads Tree image and shows in fixed position.

function drawTree() {
   var treeObj = new Image();
   treeObj.onload = function() {
   gameContext.drawImage(treeObj, 520, 110);
  };
treeObj.src = 'images/tree.png';
}

Method to clear the canvas after every animation

function clearScreen() {
    gameContext.clearRect(0, 0, gameCanvas.width, gameCanvas.height);
}

Method which moves our car image to the carX position

function moveCar() {
    clearScreen();
    drawTree();

    carX = carX + 10;
    drawCar(carX);

    if (carX >= 435) { //435px is the meeting point for tree & car image
        bangCar();
    }
}

Method assigns events to buttons runtime

function assignEventsToButtons() {
    $("#startBtn").click(function() {
        //Call moveCar() function every 250 millisecond
        animationObj = setInterval('moveCar()', 250);
    });

    $("#stopBtn").click(function() {
        stopCar();
    });

    $("#reverseBtn").click(function() {
        carX = carX - 100;
    });
}

Method clear the interval/timer & stops the animation

function stopCar() {
    clearInterval(animationObj);
}

Method shows bang image when car hits tree & reset the car position

function bangCar() {
    var bangObj = new Image();
    bangObj.onload = function() {
        gameContext.drawImage(bangObj, 580, 250);
    };
    bangObj.src = 'images/bang.png';

    stopCar();
    carX = 0;
}

You can download the source code here (car_game.zip) and here is the demo.

Category: HTML5, Javascript | Tags: , , , , ,  | Leave a Comment
Author:
Friday, January 18th, 2013

This is continuation to my previous blog. In the blog, we will see the basic structure of a user script on Chrome browser using Tampermonkey.

Step 1: Install Tampermonkey add on for Chrome browser.

Step 2:  Add a new script by clicking on “Add a new script…” option.

Pic1

Step 3: You will see script editor

Pic2

Step 4:  Add the following code on line # 9.

alert(“Hello World!”);

Step 5:  Save and open any web site, you will be greeted with “Hello World!”.

That’s it, you wrote your first user script :)

Now, let’s pay a closer look at what we just did.

Predefined Code

Line 1: // ==UserScript==
Line 2:// @name My Fancy New Userscript
Line 3:// @namespace http://use.i.E.your.homepage/
Line 4:// @version 0.1
Line 5:// @description enter something useful
Line 6:// @match http://*/*
Line 7:// @copyright 2012+, You
Line 8:// ==/UserScript==

Predefined Code Description

Line 1: User comment
Line 2: Name of the user script
Line 3: Namespace of the user script
Line 4: Version of the script. We can have a script with same name with different versions
Line 5: Description of the script
Line 6: This is the most important attribute. This specifies on which websites the script should run. In our case,  http://*/* indicates run on all sites
Line 7: Include any copyright information
Line 8:User comment

In next blog we will explore little more complex example. Have fun.

 

Category: Javascript  | Leave a Comment
Author:
Monday, December 31st, 2012

User scripts are a handy little concept through which we can extend / customize behavior of any web site. Before we talk what user scripts are, lets see what kind of things we can do with it

  • Always display some information like time or how much time you are spending on that website etc.
  •  Remove ads from your favorite web site such as Facebook  or any news site
  • Extend or implement some functionality on web sites you like. For e.g. download albums from facebook.
  • Do some time sensitive actions such as log into a web site as soon as its up. (handy when you have to book train tickets through IRCTC Tathkal)

So, what is a user script?  It’s a script which your browser can understand and act on it.  So how is it different from Javascript or vb script? The key difference is, all these client side scripts have to be part of a web application, where as user scripts sit on browser and gets injected into every site (or selected sites)  that you open in a browser. These scripts are loaded before any scripts are loaded on the page and hence the advantage.

These user scripts are specific to browser as they act as extensions to web browser. There are lot of browser extensions out there to manage and create user scripts such as Greasemonkey for firefox,  Tampermonkey

In next blog,  we will see how to use Tampermoney to create user scripts and introduce a custom behavior for a web site.

Category: Javascript | Tags:  | One Comment
Author:
Thursday, August 02nd, 2012

JavaScript performance is always a question of debate in web development. Bulk of JavaScript’s problem in client side programming is due to its blocking nature. Most of the browsers use a single process for UI updates and JavaScript execution. Longer the time it takes for JavaScript execution longer the browser is locked for updating contents on the web page.

The following are refreshers for improving JavaScript performance.

i) Place <script></script> tag always at the bottom of the page.
<html>
<head></head>
<body>
<div>..</div>
<script>JavaScript Code Snippet</script>
</body>
</html>

ii) Group multiple JavaScript files together.  It always faster to load one 100KB file than to load four 25KB files.

iii) Minification and Obfuscation – Sure minification and obfuscation helps but not at the cost of losing readable content.

iv) XHR – Though XHR addresses bulk of the synchronous loading nature of JavaScript it still has cross-domain policy issues. XHR also doesn’t address dependency management.

To address the blocking nature and the dependency management functionalities in JavaScript we use Script Loaders.

One of the more popular framework for Script loaders available today is RequireJS.

i) RequireJS addresses blocking nature of JavaScript by loading just one JavaScript file and releases the browser process for UI.
<script data-main=“scripts/main” src=“scripts/require.js”></script>

This script requires you to load require.js. User scripts will be located in a file called main.js under scripts folder. User scripts are loaded asynchronously.

ii) RequireJS also addresses dependency management by loading scripts on demand
require(["scripts/jquery"], function($) {
$(“display”).html = “This is my text”;

});

This script will add jQuery module to the application.

….. More about RequireJS and its functionality in future sessions.

Category: Javascript  | 2 Comments
Author:
Wednesday, April 27th, 2011

In Javascript, we can add our own custom methods to Javascript’s global classes during runtime.

String, Date, Array, Boolean, Math, Number are some of the JS classes. Every class has its own built-in methods. Like, “String” Class has toLowerCase(), indexOf(), etc
“Date” class has getTime(), getDay(), getFullYear(), etc.
“Array” class has pop(), sort(), etc…

We can add our custom methods during runtime using keyword “prototype”

For eg: If I want to add a method “myCurrency” to the “Number” class.

Number.prototype.myCurrency= function(){

        currencySymbol="$";
        var price  = this.valueOf();

        return currencySymbol + price;
}

var price = 20; alert (price.myCurrency());

Result: $20

Eg 2: If I want to add a custom method “detail” to “Array” class. From that method, I need to get the length of the array, first element & last elements value.

Array.prototype.detail= function(){
        return "Length = " + this.length + ", First Element = " + this[0] + ", Last Element = " + return [this.length-1];
}

var myArray = ["iSense","Prowareness","Prabhu"];; alert (myArray.detail());

Result: Length = 3, First Element = iSense, Last Element = Prowareness

Download code

Enjoy Coding :)

Author:
Thursday, March 24th, 2011

First Let’s discuss about the issue of loading all the javascript files together at a stroke.

  1. 1. Javascript will not allow parallel download. So the browser will not start any other download until it loads the javascripts.
  2. 2. We use to load javascript files and methods which are unnecessary for that page. For eg: In Login page, we just need some javascripts essential for Login page, but developers will add all the javascripts in common headers.

<script language =”javascript” src=”scriptRequiredForUserProfile.js”></script>
<script language =”javascript” src=”scriptRequiredForAddComment.js”></script>
<script language =”javascript” src=”scriptRequiredForReply.js”></script>

<script language =”javascript” src=”scriptRequiredForAddComment.js”></script>

<script language =”javascript” src=”scriptRequiredForReply.js”></script>

How to solve the above 2 issues???

  • Include only one script in the header.

<script src="”loadJS.js”"></script>

Now we can load the javascript dynamically using 2 ways.

Method 1:

Generate dynamic // <![CDATA[
tag using DOM

Maintain the list of javascripts that you need to download for a respective page.

var jsFilesArray = new Array();
jsFilesArray['home.html'] = new Array( ‘validation.js’, ‘home.js’ );
jsFilesArray['login.html'] = new Array( ‘validation.js’, ‘error.js’ );

Code to get File Name of the current page

function getCurrentPageName() {
    var fileName = document.location.href;
    var end = (fileName.indexOf("?") == -1) ? fileName.length : fileName.indexOf("?");
    return fileName.substring(fileName.lastIndexOf("/")+1, end);
}

Code to generate dynamic tag and append to the head tag.

var head = document.getElementsByTagName("head")[0];

for (var i = 0;i<jsFilesArray[getFileName()].length;i++)
{
  script = document.createElement('script');
  script.id = "id_" + i;
  script.type = 'text/javascript';
  script.src = jsFilesArray[getCurrentPageName ()][i];
  head.appendChild(script);
}

Click to download the code.

Method 2:

Use AJAX to load the JS file dynamically whenever required

Get the required JS file using xmlHttPRequest and execute the output by passing it into eval() method. The eval() method executes the argument.

So guys, load your Javascripts dynamically and experience improved performance of your application.

Enjoy Coding :)

Author:
Thursday, June 03rd, 2010

Many guys think that Javascript is a client side scripting language, its just used for client side form validations. But this proved false once AJAX come into picture. We will discuss some questions on this.

Is Javascript Object Oriented scripting language?

Many people will say no. But it is Object oriented. Javascript is a prototype-based object-oriented  scripting language.

Now, another question arises, what is that “prototype-based”?

Wikipedia defines Prototype-based programming as a style of object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based
languages) is performed via a process of cloning existing objects that serve as prototypes.

Anoter question arises “classes are not present”, then how will I create class and object????

In Javascript, your function = Class. hmmm, lot of confusions right?

I think it will be easy if we compare a programming language to understand it better. We will take Java as our reference language.

What is class?
A class is a construct that is used as a blueprint  (or template) to create objects  of that class.

What is Object?
An object is usually taken to mean a compilation of attributes (object elements) and behaviors (methods or subroutines) encapsulating  an entity.

We will write a simple Class in Java

public class Theatre{

        String theatreName;
        int noOfSeats = 80;

        public int getNoOfSeats() {
                return noOfSeats;
                }

        public String getTheatreName() {
                return theatreName;
                }

        public void setTheatreName(String newTheatre) {
                this.theatreName = newTheatre;
                }
}

Equivalent Javascript code

//Class Theatre

function Theatre(){
	this.theatreName='PVR Cinemas';
	this.noOfSeats = 80;

	this.getNoOfSeats = function() {
		return this.noOfSeats;
		}

	this.settheatreName = function(newTheatreName) {
		this.theatreName = newTheatreName;
		}

	this.gettheatreName = function(){
		return this.theatreName;
	}
}

// Create an instance of the Theatre Class
var theatre = new Theatre();
alert(theatre.gettheatreName());
theatre.settheatreName('Hitman Theatre');
alert(theatre.gettheatreName());
alert(theatre.getNoOfSeats());

I think after comparing these two code samples, you guys were clear with the concept of class in Javascript.

How to use NameSpace in Javascript?

In Java language, package names are used to prevent naming collisions and also for organizing Java classes similar to the modules of Modula. In javascript this can be achieved by object hierarchies. We will see with an example

//create the base Package object if it does not exist.
if (!Package) {
var Package = new Object();
}
// define Person under Package
Package.Person = function () {
	this.name='Albert';
	this.age = 27;
	this.changeHisAge = function(age) {
		this.age = age;
	}
}

//create an instance of the Person
var person = new Package.Person();
person.changeHisAge(28);
alert(person.name + ", age : " + person.age);

How to do Inheritance?

Here comes the keyword called “prototype”. Prototype is a type of inheritance in JavaScript. Its used to add a method to a class. Take the previous example. If we want to add a method “changeHisName”, then code follows below

Package.Person.prototype.changeHisName = function(name) {
	this.name = name;
}

How to handle Visibility or Access level of my variables and methods?

Public properties         this.variableName
Private Properties        var variableName

Public Method              ClassName.prototype.func_name = function() {}
Private Method             var func_name = function() {}
Privilige Method           this.func_name = function() {}

How to handle Singleton pattern in Javascript?

The singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object. Its very simple, hold the current object in a variable, if it exists return the same object or create a new one. Implementation is as follows:

SingletonClass = function(name){
	if(SingletonClass.object !== undefined)
		return SingletonClass.object;
	this.name = name;
	SingletonClass.object = this;
} 

var firstInstance = new SingletonClass('iSense');
alert(firstInstance.name);
//Alerts "iSense"
var secondInstance = new SingletonClass('Prabhu');
alert(secondInstance.name);
//Alerts alerts "iSense"

You can download the code used to explain.

Uses of Object Oriented javascript:
1. Reusability of the code increases
2. Dynamic loading of objects
3. Objects are organized better

Dude, start using object oriented javascript, Enjoy Coding :)