Tuesday 11 March 2014

Javascript : How to debug?

Debugger -
It allows you to find the mistakes in your written programme
There can be chance that you would make a mistake while writing your programme.
and that mistake is referred to as a bug.

The process of finding and fixing bugs is called debugging and is a normal
part of the development process.

Now we will discuss tools and techniques that can help you to debug code.

I am using chrome as Example :

To see where error is throwing
-enter F12 (which will open inspect element) -> go to console
-you'll see character written with red color (showing error)
-see the rightmost side of error characters -> some js file will be there
->click on js file it will show you the error location
                                         
To debug the code :
In previous example we understood how to find the place of error in js file
Now we will fix the error
-> put the "debugger;" (without quotes) just before error is throwing or just
   inside the function in which error exist

Example :

function checkthis(){
debugger;
// your code here
}

Note :
while debugging you can go to console and check the value of variables

Example:

funtion checkthis(data){
debugger;
var b = data.item; // you can check this b value in console after debugger stepover this line
}

Javascript validator tools :
The most convenient validator for JavaScript is Douglas Crockford's
JavaScript Lint.
http://www.jslint.com/

Monday 24 February 2014

Basic of Browsers

Bowsers : It signifies the webpage.A platform where webpage loads
               there are many different types of browser available with some different
               and its unique capability
               It is important to understand the differences between different browsers
               in order to handle them in the way we expected. So it is important
               to know which browser your Web page is running in.

To get information about the browser your Web page is currently running in,
use the built-in navigator object.

Navigator Properties:
There are several Navigator related properties that you can use in your
Web page. The following is a list of the names and descriptions of each:

Property                                                       Description

appCodeName  - contains the code name of the browser, Netscape for Netscape
                               and Microsoft Internet Explorer for Internet Explorer.
appVersion   -    contains the version of the browser as well as other useful information such as
                                its language and compatibility.
language     - contains the two-letter abbreviation for the language that is used by
                        the browser. Netscape only.
mimTypes[]   - This property is an array that contains all MIME types supported by
                        the client. Netscape only.
platform[]   - contains the platform for which the browser was compiled. "Win32" for 32-bit Windows                               operating systems
plugins[]    - It is an array containing all the plug-ins that
                       have been installed on the client. Netscape only.
userAgent[]  - contains the code name and version of the browser.
                         This value is sent to the originating server to identify the client

Example :

<html>
<head>
<title>Browser Detection Example</title>
</head>
<body>
<script type="text/javascript">

var userAgent   = navigator.userAgent;
var opera       = (userAgent.indexOf('Opera') != -1);
var ie          = (userAgent.indexOf('MSIE') != -1);
var gecko       = (userAgent.indexOf('Gecko') != -1);
var netscape    = (userAgent.indexOf('Mozilla') != -1);
var version     = navigator.appVersion;

if (opera){
  document.write("its Opera ");

}else if (gecko){
  document.write("its Mozilla");

}else if (ie){
  document.write("its IE ");

}else if (netscape){
  document.write("its Netscape");

}else{
  document.write("Unknown browser");
}

document.write("<br /> Browser version info : " + version );

</script>
</body>
</html>
NOTE : you can type and test code in console (press F12) and check the navigator.useragent

Wednesday 19 February 2014

Basics of Error Handling

Error Handling : When an error occurs user need to handle that error accordingly
                            and the method of handling these kind of error we called as Error Handling

There are three types of errors in programming:
(a) Syntax Errors
(b) Runtime Errors
(c) Logical Errors:

Syntax errors:
Syntax errors, as name denotes error caused by improper syntax
it is also called parsing errors, occur at compile time

Example:

<script type="text/javascript">

window.alert(; // syntax should be window.alert();  missing a closing parenthesis:

</script>

Runtime errors:
Runtime errors, as its name says the error happened on unning the script
it is also called exceptions, occur during execution after compilation.

Example :

<script type="text/javascript">

window.welcomeMe(); // there is no function name welcomeMe hence it throws error

</script>

Logical errors:
Logic errors is type of error which caused by wrong Logical implementation
it is most difficult type of errors to track down.
These errors are not caused by syntax or runtime error.

You can not catch those errors, because it depends on your
requirement what type of logic you want to put in your program.

The try...catch...finally Statement:
The latest versions of JavaScript comes with exception handling capabilities.
JavaScript implements the try...catch...finally and  construct as well as the
throw operator to handle exceptions.

You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript syntax errors.

Here is the try...catch...finally block syntax:

<script type="text/javascript">

try {
    // Code to implement
    break;
} catch ( e ) {
    // Code to implement if an exception occurs
    break;
} finally {
    // Code that is always executed regardless of
    // an exception occurring
}

</script>

Example :

<script>
function myFunction()
{
   var val = 100;
 
   try {
      alert("Value of variable a is : " + val );
   }catch ( e ) {
      alert("Error: " + e.description );
   }finally {
      alert("Finally block will always execute!" );
   }
}
</script>

Monday 17 February 2014

Understanding DOM (Document Object Model)

DOM stands for - Document Object Model

A Document object represents the HTML document that is displayed in a web page.
The Document object has various properties that refer to other objects which allow
access to and modification of document content.

The way that document content is accessed and modified is called the
Document Object Model, or DOM. The Objects are organized in a hierarchy.
This hierarchical structure applies to the organization of objects in a Web document.

It provides a structured representation of the document (a tree) and it defines a way
that the structure can be accessed from programs.it connects web pages to scripts or
programming languages.

Window object: Top of the hierarchy. It is the outermost element of the DOM hierarchy.

Document object: Each HTML document that gets loaded inside a window becomes a
document object. The document contains the content of the page.

Here is a simple hierarchy of few important objects:

Top most part ----------------------
HTML DOM
bottom most part

So, if you want to access button you have to load form and then only 
you can do stuffs on button , same for text and checkboxes

Wednesday 12 February 2014

Basics of Regular Expressions

A regular expression is an object that explains a pattern of characters.

The JavaScript RegExp class represents regular expressions, and both
String and RegExp define methods that use regular expressions.
To perform pattern-matching and search-and-replace functions on text we use
Regular expressions

Syntax:
A regular expression could be defined with the RegExp( ) constructor like this:

var pattern = new RegExp(pattern, attributes);
OR
var pattern = /pattern/attributes;
Here is the description of the parameters:

pattern: A string that specifies the pattern of the regular expression or
           another regular expression.

attributes: An optional string containing any of the "g", "i", and "m" attributes
              that specify global, case-insensitive, and multiline matches, respectively.

[...]Any one character between the brackets.
[^...]Any one character not between the brackets.
[0-9]It matches any decimal digit from 0 through 9.
[a-z]It matches any character from lowercase a through lowercase z.
[A-Z]It matches any character from uppercase A through uppercase Z.
[a-Z]It matches any character from lowercase a through uppercase Z.

Examples :
<html>
<body>
<p id="demo">Click the button to do a case-insensitive search for "India" in a string.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var str = "Visit India";
var patt1 = /India/i;
var result = str.match(patt1);
document.getElementById("demo").innerHTML=result;
}
</script>
</body>
</html>

<html>
<body>
Global pattern Matching:
Pattern value is added with "/g" which denotes global

Example:
<p id="demo">Click the button to do a global search for "is" in a string.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var str = "Is this all there is?";
var patt1 = /is/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML=result;
}
</script>
</body>

</html>

Wednesday 5 February 2014

Working with Objects


Objects are made of attributes. If an attribute contains a function,
then we considered it is a method of the object otherwise, the attribute is considered a property.

The syntax for adding a property to an object is:

objectName.objectProperty = propertyValue;
Example:

var str = document.title;

Object Methods:

The methods are functions that tell the object do something or let something
be done to it. There is little difference between a function and a method,
except that a function is a standalone unit of statements and a method is
attached to an object and can be referenced by the this keyword.

Methods are useful for everything from displaying the contents of the object
to the screen to performing any complex mathematical operations on properties and parameters.

Example:

document.write("This is test");

User-Defined Objects:

All user-defined objects and built-in objects are composed of an object.

The new Operator:

The new operator is used to create an instance of an object. To create an object,
the new operator is followed by the constructor method.

In the following example, we see the constructor methods are Object(), Array(), and Date().
These constructors are built-in JavaScript functions.

var employee = new Object();
var books = new Array("C", "Perl", "Javascript");
var day = new Date("August 15, 1947");

The Object() Constructor:

A constructor is a function that creates and initializes an object.
JavaScript provides a special constructor function called Object() to build
the object. The return value of the Object() constructor is assigned to a variable.

The variable contains a reference to the new object. The properties assigned
to the object are not variables and are not defined with the var keyword.

Example 1:
create an object:

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
var book = new Object();   // Creating the object
    book.subject = "Perl"; // Assign properties to the object
    book.author  = "Mohtashim";
</script>
</head>
<body>
<script type="text/javascript">
   document.write("Book name is : " + book.subject + "<br>");
   document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>

Example 2:

Creating an object with a User-Defined Function.
Here this keyword is used to refer to the object that has been passed to a function:

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
function book(title, author){
    this.title = title;
    this.author  = author;
}
</script>
</head>
<body>
<script type="text/javascript">
   var myBook = new book("Perl", "Mohtashim");
   document.write("Book title is : " + myBook.title + "<br>");
   document.write("Book author is : " + myBook.author + "<br>");
</script>
</body>
</html>

Defining Methods for an Object:

Example:

Here is a simple example to show how to add a function along with an object:

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">

// Define a function which will work as a method
function addPrice(amount){
    this.price = amount;
}

function book(title, author){
    this.title = title;
    this.author  = author;
    this.addPrice = addPrice; // Assign that method as property.
}

</script>
</head>
<body>
<script type="text/javascript">
   var myBook = new book("Perl", "c++");
   myBook.addPrice(100);
   document.write("Book title is : " + myBook.title + "<br>");
   document.write("Book author is : " + myBook.author + "<br>");
   document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>

The with Keyword:

The with keyword is used as a kind of shorthand for referencing an
object's properties or methods.

The object specified as an argument to with becomes the default object
for the duration of the block that follows. The properties and methods
for the object can be used without naming the object.

Syntax:

with (object){
    properties used without the object name and dot
}
Example:

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">

// Define a function which will work as a method
function addPrice(amount){
    with(this){
       price = amount;
    }
}
function book(title, author){
    this.title = title;
    this.author  = author;
    this.price = 0;
    this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type="text/javascript">
   var myBook = new book("Perl", "c++");
   myBook.addPrice(100);
   document.write("Book title is : " + myBook.title + "<br>");
   document.write("Book author is : " + myBook.author + "<br>");
   document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>
Abhishek Sinha

Monday 27 January 2014

Javascript : Classes and Objects

The Class

JavaScript is basically prototype-based language which have no class statement,
as found in C++ or Java. This is actually confusing for programmers
accustomed to languages with a class statement. In reality, JavaScript uses
functions as classes. Defining a class is as easy as defining a function.

Examples:

function employee() { }

The Objects

Objects are basically instance of classes which help us to access the methods
of that class.

To create a new instance of an object obj we use the statement new obj,
assigning the result (which will be type obj) to a variable to access it later.

In the example below we define a class named employee and we
create two instances (emp1 and emp2).

function employee() { }
var emp1= new employee();
var emp2= new employee();

Monday 20 January 2014

Javascript : Prototype based programming

Prototype-based programming:
Prototype-based programming is a style of doing programming like object-oriented programming
in which instead of classes functions are present, and function's behavior reuse
is accomplished through a process of decorating existing objects which serve as prototypes.
This model is also known as prototype-oriented, or instance-based programming.

Advantage :
- Re-usability
- can maintain large number of classes with less code
- Multiple inheritance is easy
- can change behavior at runtime

Example :


Saturday 18 January 2014

Javascript : Introducing Object oriented Javascript

OOPS INTRODUCTION  :

JavaScript is not a object-oriented programming language but it has
strong capabilities of oops,even people debate have taken place
due to the differences in object-oriented JavaScript compared to
other languages.

User can create classes and object and can use in their JavaScript code.





Class

Defines the characteristics of the Object and how object should behave.

Object

An Instance of a Class and help to access method of class.

Property

An Object characteristic, such as color,size,alignment.

Method

It defines Activity and behaviour, such as walk.

Constructor

A method called at the moment of instantiation.

Inheritance

A Class can inherit characteristics from another Class i.e from base class.

Encapsulation

A Class defines only the characteristics of the Object . It provide security to code .

Abstraction

The conjunction of complex inheritance, methods, properties of an Object must be able to simulate a reality model.

Polymorphism

Different Classes might define the same method or property.
Having same look but acted differently on different places

NOTE :  Javascript is a prototype of  object oriented language but it a bit confusing for
              programmer because javascript functions used as class

Friday 17 January 2014

Javascript : Understanding Dailog boxes

JavaScript supports three types of dialog boxes. 
Dialog box are very useful to throw a kind of message or alert to user
or to get confirmation on any input or to have a kind of input from the users.

Alert Dialog Box:

An alert dialog box is mostly used to give a warning message to the users.
one input field requires to enter some text but user does not
enter that field then as a part of validation you can use alert box to
give warning message as follows:

<head>
<script type="text/javascript">

   alert("Warning !!");

</script>
</head>
Alert box gives only one button "OK" to select and proceed.

Confirmation Dialog Box:

A confirmation dialog box is mostly used to take user's consent on any option.
It displays a dialog box with two buttons: OK and Cancel.

If the user clicks on OK button the window method confirm() will return true.
If the user clicks on the Cancel button confirm() returns false.

<head>
<script type="text/javascript">

   var Val = confirm("Do you want to continue ?");
   if( Val == true ){
      alert("User wants to continue!");
 return true;
   }else{
      alert("User does not want to continue!");
 return false;
   }

</script>
</head>
To understand it in better way you can Try it yourself.

Prompt Dialog Box:

The prompt dialog box is very useful when you want to pop-up a text box to get user input.
it enable you to interact with the user. User needs to fill in the field and then
click OK.

This dialog box is displayed using a method called prompt() which have two parameters
(i) A label which you want to display in the text box
(ii) A default string to display in the text box.

This dialog box with two buttons: OK and Cancel.
If the user clicks on OK button
the window method prompt() will return entered value from the text box.
If the user clicks on the Cancel button the window method prompt()
returns null.

<head>
<script type="text/javascript">
   var Val = prompt("Enter your name : ", "your name");
   alert("You have entered : " +  Val );
</script>
</head>

Wednesday 15 January 2014

Javascript : Working with Cookies - Part - 2

Storing Cookies:

We can create a cookie and assign it to a string value to the document.cookie object:
Syntax:
document.cookie = "key1=value1;key2=value2;expires=date";
if we set cookie with given date and time the cookie will expires and
cannot be accessible

Note: Cookie values may not include semicolons, commas, or whitespace. For this reason,
you may need to use the JavaScript escape() function to encode the value before storing
it in the cookie. and unescape() function to read the cookie

Reading Cookies:
Reading a cookie is just as simple as writing one, because the
value of the document.cookie object is the cookie. So you can
use this string whenever you want to access the cookie.

The document.cookie string will keep a list of name=value pairs
separated by semicolons, where name is the name of a cookie and
value is its string value.

You can use strings' split() function to break the string into
key and values as follows:


Deleting a Cookie:
Sometimes you will want to delete a cookie so that subsequent attempts to 
read the cookie return nothing. To do this, you just need to set the 
expiration date to a time in the past.


Sunday 12 January 2014

Javascript : Working With Cookies - Part -1

Cookies : 
               When a small piece of information sent from website & stored in user's web-browser                during the time of browsing 

 For example : 
                     User Login information stored in cookies , whenever user request that particular                      web page the cookies fill the information
Note :
            Every time the user loads the website, the browser sends the cookie back to the                       server to notify the website of the user's previous activity

Understand Working :
  
  -> Server send data to user web browser in form of cookies
  -> User may allow to accept cookies or can reject it
  -> If user accept cookies then the cookies store in plain text in user system
  -> server remember the location and can retrieved the store information

Cookies stored with the following field
  • Expires : The date the cookie will expire. If this is blank, the cookie will expire when                       the visitor quits the browser.
  • Domain : The domain name of your site.
  • Path : The path to the directory or web page that set the cookie. This may be blank if                  you want to retrieve the cookie from any directory or page.
  • Secure : If this field contains the word "secure" then the cookie may only be retrieved                   with a secure server. If this field is blank, no such restriction exists.
  • Name=Value : Cookies are set and retrieved in the form of key and value pairs.

Next Blog we will see how many types of cookies are available ...

Wednesday 8 January 2014

Javascript : Page Redirection & Page Refresh

Javascript (JS) :

Page Redirection : 
                             It is a process by which URL which user typed for accessing page - X but
                             internally redirected to some other page
                       
Example:
type : www.fb.com
        it will redirect you to www.facebook.com

Example 1:

<head>
<script type="text/javascript">

   window.location="http://www.newpage.com";

</script>
</head>

Why Page - redirection is USEFUL ?

-For commercial website which have different product in different countries
-Publisher of website don't want to loose their visitors , so they buy all common domain which resembles
  their website name

You can set message also during Page-redirect :

Example :
<head>
<script type="text/javascript">

function Redirectme()
{
    window.location="http://www.newpage.com";
}

document.write("You will be redirected to main page in 5 sec.");
setTimeout('Redirectme()', 5000);
</script>
</head>

Page Refresh : 
                        It actually reload the page by calling reload method
                        Location.reload() method
                        if You pass location.reload(true) - will load page from server
                        otherwise it will reload from cache

Thursday 2 January 2014

Javascript : Events

What is an Event ?
Occurrence of an activity termed as Event
JavaScript's interaction with HTML is handled through events
that occur when the user or browser works on a page.

When the page loads,even occurs. When the user clicks a button,
that click, too, is an event, pressing any key,
closing window, re sizing window etc.

Events are a part of the Document Object Model (DOM) Level 3 and every
HTML element have a certain set of events which can trigger JavaScript Code.

onclick Event Type:
This is the most frequently used event type which occurs when a user
clicks mouse left button. You can put your validation, warning etc against this event type.

Example:

<html>
<head>
<script type="text/javascript">

function begin() {
   alert("Hello World")
}

</script>
</head>
<body>
<input type="button" onclick="begin()" value="welcome" />
</body>
</html>
This will produce following result and when you click Hello
button then onclick event will occur which will trigger begin() function.

onsubmit event type:
Another most important event type is onsubmit.
This event occurs when you try to submit a form.
So you can put your form validation against this event type.

Here is simple example showing its usage. Here we are calling a validate()
function before submitting a form data to the webserver. If validate()
function returns true the form will be submitted otherwise it will not submit the data.

Example:

<html>
<head>
<script type="text/javascript">

function validation() {
   do validation ...
   .........
   return either true or false
}

</script>
</head>
<body>
<form method="POST" action="check.aspx" onsubmit="return validate()">
.......
<input type="submit" value="Submit" />
</form>
</body>
</html>
onmouseover and onmouseout:
These two event types will help you to create nice effects with images
or even with text as well. The onmouseover event occurs when you bring your
mouse over any element and the onmouseout occurs when you take your mouse out from that element.

Example:

Following example shows how a division reacts when we bring our mouse in that division:

<html>
<head>
<script type="text/javascript">

function onOver() {
   alert("Mouse Over");
}
function Onout() {
   alert("Mouse Out");
}

</script>
</head>
<body>
<div onmouseover="Onover()" onmouseout="Onout()">
<h2> This is inside the division </h2>
</div>
</body>
</html>

Events and their description :
                                                                 

Wednesday 1 January 2014

Javascript : Understanding Functions

Javascript(JS):
JavaScript Functions :
A function is a group of reusable code which can be called anywhere in your program.
its help us to eliminates the need of writing same code again and again. it helps
programmers to write modular code. You can break your big program in a number of small and operable functions.

Like any other advance programming language, JavaScript also supports all the features
necessary to write modular code using functions.

some predefined function are alert() , write() , confirm();

JavaScript allows us to write our own functions as well.
This section will explain you how to write your own functions in JavaScript.

Function Definition:
Before we use a function we need to define that function.
The most common way to define a function in JavaScript is by using the "function" keyword,
followed by a unique function name, with some parameters (that might be empty),
and a statement block surrounded by "{}" curly braces. The basic syntax is shown here:

<script type="text/javascript">

function name(parameter-list)
{
  your statement......
}

</script>
Example:

A simple function that takes no parameters called "begin" is defined here:

<script type="text/javascript">

function begin()
{
   alert("hello javscript");
}

</script>
Calling a Function:
To invoke a function somewhere later in the script,
just write the name of that function as follows:

<script type="text/javascript">

begin();

</script>

Function Parameters:
we have seen function without a parameters. But there is a
facility to pass different parameters while calling a function.
These passed parameters can be captured inside the function and
any operation can be done over those parameters.

A function can take multiple parameters separated by comma.

Example:

This time it will take three parameters:

<script type="text/javascript">

function begin(name, place , year)
{
   alert( name + " is from this " + place + "from" + year );
}

</script>
Note: Use + operator to concatenate string and number together.
JavaScript does not mind in adding numbers into strings.

Now we can call this function as follows:

<script type="text/javascript">

begin('Zara', 'bangalore', 1988 );

</script>
To understand it in better way you can Try it yourself.

The return Statement:
A JavaScript function can have a return statement.
if you want to return a value from a function.

For example :
you can pass two numbers in a function and you can return the output of that function

Example:

The function takes two parameters and combine them and return result. Take a look

<script type="text/javascript">

function hello(first, second)
{
   var result;
   result = first + second;
   return  result; // result have the output which will be return where ever this function being called
}

</script>
Now we can call this function as follows:

<script type="text/javascript">

   var value;
   value = hello('hello', 'world');
   alert(value );

</script>