Archive

Archive for the ‘JavaScript’ Category

sigma.js

August 7, 2012 Leave a comment

sigma.js is a free and open-source JavaScript library to draw graphs, using the HTML5 canvas element. It has been especially designed to share interactive network maps on a Web page or to explore dynamically a network database.

sigma.js Examples

Categories: Canvas, HTML5, JavaScript

Repo.js

August 7, 2012 Leave a comment

Repo.js is a light-weight jQuery Plugin that lets you easily embed a Github repo onto your site. As a plugin or library author this is a great way to showcase the contents of a repo on a project page.

Repo.js github page

Categories: JavaScript, Tools

JavaScript String: Single or Double Quote?

August 7, 2012 1 comment

If you come from a strongly typed language like C++ to JavaScript you’ll definitely confused the way strings are represented in it.

In JavaScript you can use both single and double quotes to represent a string. Also you can use both single and double quotes in a single line too but the nesting order should be maintained ie if you start a double or single quote then you must finish it before using a different quote. For example

var strStudentName = "Tom" + ' Thomas'; //Correct 
var strStudentAddress = "12/56, ' + 'Arizona "; //Incorrect; due to the quote nesting issues

So the best part is the user can represent the string in JavaScript any way they want. But a question at this point is which method is the proper one?

There is no definite answer as both single and double quotes are interchangeable and you can use whatever you find convenient.

Still I feel that we should use single quotes in JavaScript to represent strings. One of the reason I found is this style is useful especially if you are dealing with HTML markup strings in JavaScript. In HTML the double quotes used for storing attributes. An example would be

var strHtml = '<div id="p0_content">This is a test</div>";

In the above code snippet we’ve used single quote for the string value and double quotes for enclosing the attribute value in the markup. It looks simple and elegant.

Categories: JavaScript

Identifying an array in JavaScript

July 7, 2011 3 comments

In JavaScript using typeof operator we can find the type of the variable used in the script. But it sometimes produce some confusing values for the developer especially for the novice ones. Consider the following code

var foo = {
	'name': 'Jayaprakash',
	'job': 'Web Team Lead'
};

If you want to determine the type of the object literal foo it is quite simple

console.log(typeof foo); //Outputting it to the browser console

The output would be ‘object‘. Pretty simple, right?

Now consider an example with an Array

var foo = [];
foo.push(1);
foo.push(2);

You want to determine the type of the array vaiable foo

console.log(typeof foo);

The output would be ‘object‘. Bit confusing you may be expecting array as the output. This is because JavaScript treats arrays as object (most of the items in JavaScript are considered as objects) in it. As a result when you determine the type of it, it will give you a value of object.

The question at this point is, is there any way through one can determine whether a variable is array or not? Yes we have a simple method for doing that

var isArray = function(arr){
	return Object.prototype.toString.call(arr).toLowerCase().indexOf('[object array]') !== -1;
}

This function will return true if the argument is a JavaScript array else it will return false.

Categories: JavaScript

JavaScript Password Generator

Yesterday one of my friend contacted me for a simple JavaScript password generator that he wants to use in their Intranet.

Like everyone I thought of depending on Google, but after hearing his requirements I thought of making one myself. The code may seem bit specific as I’ve done this for a very specific requirement.

function generatePassword(type, plen){
	var lwrAlph = "abcdefghijklmnopqrstuvwxyz",
		uprAlph = "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
		nums = "0123456789",
		spl = "~!@#$%^&*()-_=+|<>,.;:[]{}",
		passwd = [],
		maxLen = 32,		
		defLen = 8,
		minLen = 5;		

	/*Parameter Manipulations*/
	type = type || "all";
	type = isNaN(type)?type.toLowerCase():"all";	
	plen = plen || defLen;
	plen = (plen < 0?defLen:(plen <= maxLen? (plen < minLen?defLen:plen): maxLen));
	
	/*Choosing the password source characters*/	
	src = type === "alpha"? [lwrAlph, uprAlph]:type === "alphanum"?[lwrAlph, uprAlph, nums]:[lwrAlph, uprAlph, nums, spl];
	
	/*Password construction*/	    
    for (var i = 0; i < plen; i++) {
        var rnd = Math.floor(Math.random() * src.length),
			charBuild = src[rnd].split("");		     
        rnd = Math.floor(Math.random() * charBuild.length);
        passwd.push(charBuild[rnd]);
    }
    
    return passwd.join("");
}

The function accepts two parameters. The first one denotes type, which tells the routine what kind of characters should be used. This parameter can have 3 possible values: all, alpha and alphanum.

If you use value all the generated password can use alaphabets (lower & upper), numbers and special characters.

If you use alpha the generated password can use alaphabets (lower & upper).

If you use alphanum the generated password can use alaphabets (lower & upper) and numbers.

The second parameter denotes the length of the password going to generate. It has a restriction of 32 characters maximum and 5 characters minimum. If the user do not specify the length the a length would be selected by the code, which is 8. So it might be bit confusing at first but it is straight one once you check the logic.

I have furnished some test function calls that I’ve done earlier during a small testing period.

console.log(generatePassword("", -1));
console.log(generatePassword(""));
console.log(generatePassword());
console.log(generatePassword(null, null));
console.log(generatePassword(undefined, undefined));
console.log(generatePassword("alpha", 8));
console.log(generatePassword("alphanum", 8));
console.log(generatePassword("alphanum", 33));
console.log(generatePassword(-1));
console.log(generatePassword(1));
console.log(generatePassword("alphanum", 3));

I was using my Firebug console for checking the outputs of the function.

Easy Firebug Console Logging

January 21, 2010 Leave a comment

Like most of the web developers I too develop the pages using Mozilla Firefox with the help of the Firebug extension. After making everything correct in Mozilla Firefox the next step is to test the page(s) in Google Chrome and Apple Safari. As the last step I will start my tests in Internet Explorer.

As far as the JavaScript testing is concerned I extensively uses Firebug’s console APIs in my JavaScript source code.

console.log("This is a test");
console.info("The value of name: " + name);

What I usually miss before starting the Internet Explorer tests is to remove the calls that I’ve made to the Firebug’s console object. IE breaks down its execution without any fail as it does not support a console object until IE7. As you know IE8 supports a console, which is a first attempt from microsoft to make something that we can call a better debugger.

I’ve created a small JavaScript function through which this issue can be avoided. I mean I can log whatever I want in Firebug’s console from my JavaScript as usual but even if miss to remove those calls IE will not break down saying that “Console is not defined”.

function trim(str) {
	return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
function log(obj, consoleMethod) {
	if (window.console && trim(window.console.firebug) !== '') {
		if (typeof consoleMethod === "string" && typeof console[consoleMethod] === "function") {
			console[consoleMethod](obj);
		} else {
			console.log(obj);
		}
	}
}

The function accepts two arguments.

  • The first one is the “item” that you want to log in to Firebug’s console. It can be string, object, rather anything from the JavaScript code.
  • The second one is an optional firebug’s console name in string mode. If there is nothing then the function will use log as the default option.

Typical function calls would be like the following

log("This will be logged");

log("This will be displayed in console as info", "info");

log("This will be displayed in console as error ", "error");

This is a very simple thing through which some head aches can be avoided.

Categories: JavaScript

Cross-Domain Ajax Calls: The YUI Way

January 4, 2010 8 comments

Ajax is one of the most important technology that is a part of web 2.0 applications. Unfortunately the Cross/Sub-domain communications through Ajax are not allowed in browsers due to the security restrictions imposed by them. There are few techniques through which a web developer can make Cross/Sub-domain Ajax calls. A method is using the browser’s Flash plug-in to make this communication possible. In this tutorial we are going to use the YUI framework to make Cross/Sub-domain Ajax calls.

Read more…

Categories: JavaScript