Monday, December 5

JavaScript Objects

JavaScript Objects Introduction

JavaScript is an Object Oriented Programming (OOP) language.
An OOP language allows you to define your own objects and make your own variable types.

Object Oriented Programming

JavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to define your own objects and make your own variable types.
However, creating your own objects will be explained later, in the Advanced JavaScript section. We will start by looking at the built-in JavaScript objects, and how they are used. The next pages will explain each built-in JavaScript object in detail.
Note that an object is just a special kind of data. An object has properties and methods.

Properties

Properties are the values associated with an object.
In the following example we are using the length property of the String object to return the number of characters in a string:
<script type="text/javascript">
var txt="Hello Shibashish!";
document.write(txt.length);
</script>
The output of the code above will be:
17


Methods

Methods are the actions that can be performed on objects.
In the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters:
<script type="text/javascript">
var str="Hello shibashish!";
document.write(str.toUpperCase());
</script>
The output of the code above will be:
HELLO SHIBASHISH!

How to style strings.

 <html>
<body>

<script type="text/javascript">

    var txt = "Hello Shibashish!";

    document.write("<p>Big: " + txt.big() + "</p>");
    document.write("<p>Small: " + txt.small() + "</p>");

    document.write("<p>Bold: " + txt.bold() + "</p>");
    document.write("<p>Italic: " + txt.italics() + "</p>");

    document.write("<p>Fixed: " + txt.fixed() + "</p>");
    document.write("<p>Strike: " + txt.strike() + "</p>");
  
    document.write("<p>Fontcolor: " + txt.fontcolor("green") + "</p>");
    document.write("<p>Fontsize: " + txt.fontsize(6) + "</p>");

    document.write("<p>Subscript: " + txt.sub() + "</p>");
    document.write("<p>Superscript: " + txt.sup() + "</p>");

    document.write("<p>Link: " + txt.link("http://shibashishdotnetocean.blogspot.com/2011/12/javascript-objects.html") + "</p>");

    document.write("<p>Blink: " + txt.blink() + " (does not work in IE, Chrome, or Safari)</p>");

</script>

</body>
</html>
How to convert a string to lowercase or uppercase letters.
<html>
<body>

<script type="text/javascript">

var txt="Hello Shibashish!";
document.write(txt.toLowerCase() + "<br />");
document.write(txt.toUpperCase());

</script>

</body>
</html>

How to search for a specified value within a string.

<html>
<body>

<script type="text/javascript">
var str="Hello shibashish!";
document.write(str.match("shibashish") + "<br />");
document.write(str.match("shibushish") + "<br />");
document.write(str.match("shbashish") + "<br />");
document.write(str.match("shibashish!"));
</script>

</body>
</html>

How to replace a specified value with another value in a string.

<html>
<body>

<script type="text/javascript">

var str="Visit shibashish!";
document.write(str.replace("Visit","Lovely Boy"));

</script>
</body>
</html>

How to return the position of the first found occurrence of a specified value in a string.


<html>
<body>

<script type="text/javascript">
    var str = "Hello Shibashish!";
    document.write(str.indexOf("o") + "<br />");
    document.write(str.indexOf("Shibuna") + "<br />");
    document.write(str.indexOf("Shibashish"));
</script>

</body>
</html>

JavaScript Date Object

How to use the Date() method to get today's date.


<html>
<body>

<script type="text/javascript">

var d=new Date();
document.write(d);

</script>

</body>
</html>

Use getFullYear() to get the year.

<html>
<body>

<script type="text/javascript">

var d=new Date();
document.write(d.getFullYear());

</script>

</body>
</html>

getTime() returns the number of milliseconds since 01.01.1970

<html>
<body>

<script type="text/javascript">
var d=new Date();
document.write(d.getTime() + " milliseconds since 1970/01/01");
</script>

</body>
</html>

How to use setFullYear() to set a specific date.

<html>
<body>

<script type="text/javascript">

    var d = new Date();
    d.setFullYear(2011, 10, 3);
    document.write(d);

</script>

</body>
</html>

How to use toUTCString() to convert today's date (according to UTC) to a string.


<html>
<body>

<script type="text/javascript">

    var d = new Date();
    document.write("Original form: ");
    document.write(d + "<br />");
    document.write("To string (universal time): ");
    document.write(d.toUTCString());

</script>

</body>
</html>

Use getDay() and an array to write a weekday, and not just a number.

<html>
<body>

<script type="text/javascript">

var d=new Date();
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";

document.write("Today is " + weekday[d.getDay()]);

</script>

</body>
</html>

How to display a clock on your web page.

<html>
<head>
<script type="text/javascript">
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout('startTime()',500);
}

function checkTime(i)
{
if (i<10)
  {
  i="0" + i;
  }
return i;
}
</script>
</head>

<body onload="startTime()">
<div id="txt"></div>
</body>
</html>

Create a Date Object

The Date object is used to work with dates and times.
Date objects are created with the Date() constructor.
There are four ways of instantiating a date:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Most parameters above are optional. Not specifying, causes 0 to be passed in.
Once a Date object is created, a number of methods allow you to operate on it. Most methods allow you to get and set the year, month, day, hour, minute, second, and milliseconds of the object, using either local time or UTC (universal, or GMT) time.
All dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC) with a day containing 86,400,000 milliseconds.
Some examples of instantiating a date:
var today = new Date()
var d1 = new Date("October 13, 1975 11:13:00")
var d2 = new Date(79,5,24)
var d3 = new Date(79,5,24,11,33,0)


Set Dates

We can easily manipulate the date by using the methods available for the Date object.
In the example below we set a Date object to a specific date (14th January 2010):
var myDate=new Date();
myDate.setFullYear(2010,0,14);
And in the following example we set a Date object to be 5 days into the future:
var myDate=new Date();
myDate.setDate(myDate.getDate()+5);
Note: If adding five days to a date shifts the month or year, the changes are handled automatically by the Date object itself!

Compare Two Dates

The Date object is also used to compare two dates.
The following example compares today's date with the 14th January 2100:
var x=new Date();
x.setFullYear(2100,0,14);
var today = new Date();

if (x>today)
  {
  alert("Today is before 14th January 2100");
  }
else
  {
  alert("Today is after 14th January 2100");
  }

JavaScript Array Object

simple Ex:

<html>
<body>

<script type="text/javascript">
var i;
var mynames = new Array();
mynames [0] = "shibashish";
mynames [1] = "mohanty";
mynames [2] = "Aul";
//foreach(i in mynames)
for (i=0;i<mynames .length;i++)
{
document.write(mynames [i] + "<br />");
}
</script>

</body>
</html>

What is an Array?

An array is a special variable, which can hold more than one value, at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
var car1="Saab";
var car2="Volvo";
var car3="BMW";
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
The best solution here is to use an array!
An array can hold all your variable values under a single name. And you can access the values by referring to the array name.
Each element in the array has its own ID so that it can be easily accessed.

Create an Array

An array can be defined in three ways.
The following code creates an Array object called myCars:
1:
var myCars=new Array(); // regular array (add an optional integer
myCars[0]="Saab";       // argument to control array's size)
myCars[1]="Volvo";
myCars[2]="BMW";
2:
var myCars=new Array("Saab","Volvo","BMW"); // condensed array
3:
var myCars=["Saab","Volvo","BMW"]; // literal array
Note: If you specify numbers or true/false values inside the array then the variable type will be Number or Boolean, instead of String.

Access an Array

You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0.
The following code line:
document.write(myCars[0]);
will result in the following output:
Saab


Modify Values in an Array

To modify a value in an existing array, just add a new value to the array with a specified index number:
myCars[0]="Opel";
Now, the following code line:
document.write(myCars[0]);
will result in the following output:
Opel

join two arrays-concat():

 
<html>
<body>

<script type="text/javascript">

var parents = ["jagannath", "baidyannath"];
var children = ["Raja", "shibuna"];
var family = parents.concat(children);
document.write(family);

</script>

</body>
</html>

join three arrays-concat():


 <html>
<body>

<script type="text/javascript">

var parents = ["jagannath", "baidyannath"];
var sisters= ["madhu", "sonali", "barsha"];
var children = ["Raja", "shibuna"];
var family = parents.concat(sisters, children);
document.write(family);

</script>

</body>
</html>
<html>
<body>

join all elements of an array into a string-join(): 


<script type="text/javascript">

var developer= ["Shibashish", "debashish", "sonali", "madhu"];
document.write(developer.join() + "<br />");
document.write(developer.join("+") + "<br />");
document.write(developer.join(" and "));

</script>

</body>
</html>

Remove the last element of an array-pop():

<html>
<body>

<script type="text/javascript">

var family= ["shibashish", "debashish", "madhu", "sonali"];
document.write(family.pop() + "<br />");
document.write(family+ "<br />");
document.write(family.pop() + "<br />");
document.write(family);

</script>

</body>
</html>

Add new item to the end of an array-push():

 <html>
<body>

<script type="text/javascript">
    var family = ["shibashish", "debashish", "madhu", "sonali"];
    document.write(family.push("barsha") + "<br />");
    document.write(family + "<br />");
    document.write(family.push("shibuna","raja") + "<br />");
    document.write(family);
   

</script>

</body>
</html>

Reverse the order of the element-reverse():

<html>
<body>

<script type="text/javascript">

var family = ["shibashish", "debashish", "madhu", "sonali"];
document.write(family .reverse());

</script>

</body>
</html>

Remove the first element of an array-shift():

<html>
<body>

<script type="text/javascript">

var family= ["shibashish", "debashish", "madhu", "sonali"];
document.write(family.shift() + "<br />");
document.write(family+ "<br />");
document.write(family.shift() + "<br />");
document.write(family);

</script>

</body>
</html>

Select elements from an array-slice():

<html>
<body>

<script type="text/javascript">
    var family = ["shibashish", "debashish", "madhu", "sonali"];
    document.write(family.slice(0, 1) + "<br />");
    document.write(family.slice(2) + "<br />");
    document.write(family.slice(-3) + "<br />");
    document.write(family);
   

</script>
</body>
</html>

Sort  an array (alphabetically and ascending)-sort():


<html>
<body>

<script type="text/javascript">

var family = ["shibashish", "debashish", "madhu", "sonali"];
document.write(family .sort());

</script>

</body>
</html>

Sort  numbers (numerically and ascending)-sort():


<html>
<body>

<script type="text/javascript">

    function sortNumber(a, b) {
        return a - b;
    }

    var n = ["10", "5", "40", "25", "100", "1"];
    document.write(n.sort(sortNumber));

</script>

</body>
</html>


Sort  numbers (numerically and descending)-sort():


<html>
<body>

<script type="text/javascript">

    function sortNumber(a, b) {
        return  b - a;
    }

    var n = ["10", "5", "40", "25", "100", "1"];
    document.write(n.sort(sortNumber));

</script>

</body>
</html>


Add an element to position 2 in an array -splice():


<html>
<body>

<script type="text/javascript">

    var family = ["shibashish", "debashish", "madhu", "sonali"];
    document.write("Added: " + family.splice(2, 0, "lala") + "<br />");
    //check the below comment line for better understand
    //document.write("Added: " + family.splice(2, 2, "lala") + "<br />");
    //document.write("Added: " + family.splice(2, 1, "lala") + "<br />");
    document.write(family);

</script>

</body>
</html>



Convert an array to a string-toString():


<html>
<body>

<script type="text/javascript">

var family = ["shibashish", "debashish", "madhu", "sonali"];
document.write(family .toString());

</script>

</body>
</html>

Add new element to the beginning of an array -unshift():


<html>
<body>

<script type="text/javascript">

    var family = ["shibashish", "debashish", "madhu", "sonali"];
    document.write(family + "<br />");
    document.write(family.unshift("lala") + "<br />");
    document.write(family + "<br />");
    document.write(family.unshift("raja", "shibuna") + "<br />");
    document.write(family);

</script>

</body>
</html>

JavaScript Boolean Object

Check if a Boolean object is true or false.

<html>
<body>

<script type="text/javascript">
var b1=new Boolean( 0);
var b2=new Boolean(1);
var b3=new Boolean("");
var b4=new Boolean(null);
var b5=new Boolean(NaN);
var b6=new Boolean("false");

document.write("0 is boolean "+ b1 +"<br />");
document.write("1 is boolean "+ b2 +"<br />");
document.write("An empty string is boolean "+ b3 + "<br />");
document.write("null is boolean "+ b4+ "<br />");
document.write("NaN is boolean "+ b5 +"<br />");
document.write("The string 'false' is boolean "+ b6 +"<br />");
</script>

</body>
</html>

Create a Boolean Object

The Boolean object represents two values: "true" or "false".
The following code creates a Boolean object called myBoolean:
var myBoolean=new Boolean();
If the Boolean object has no initial value, or if the passed value is one of the following:
  • 0
  • -0
  • null
  • ""
  • false
  • undefined
  • NaN
the object it is set to false. For any other value it is set to true (even with the string "false")!

JavaScript Math Object

How to use round().

<html>
<body>

<script type="text/javascript">

document.write(Math.round(0.60) + "<br />");
document.write(Math.round(0.50) + "<br />");
document.write(Math.round(0.49) + "<br />");
document.write(Math.round(-4.40) + "<br />");
document.write(Math.round(-4.60));

</script>

</body>
</html>

How to use random() to return a random number between 0 and 1. 

<html>
<body>

<script type="text/javascript">

//return a random number between 0 and 1
document.write(Math.random() + "<br />");

//return a random integer between 0 and 10
document.write(Math.floor(Math.random()*11));

</script>

</body>
</html>

How to use max() to return the number with the highest value of two specified numbers. 

<html>
<body>

<script type="text/javascript">
document.write(Math.max(5,10) + "<br />");
document.write(Math.max(0,150,30,20,38) + "<br />");
document.write(Math.max(-5,10) + "<br />");
document.write(Math.max(-5,-10) + "<br />");
document.write(Math.max(1.5,2.5));
</script>

</body>
</html>

How to use min() to return the number with the lowest value of two specified numbers. 

<html>
<body>

<script type="text/javascript">

document.write(Math.min(5,10) + "<br />");
document.write(Math.min(0,150,30,20,38) + "<br />");
document.write(Math.min(-5,10) + "<br />");
document.write(Math.min(-5,-10) + "<br />");
document.write(Math.min(1.5,2.5));

</script>

</body>
</html>

Math Object

The Math object allows you to perform mathematical tasks.
The Math object includes several mathematical constants and methods.
Syntax for using properties/methods of Math:
var x=Math.PI;
var y=Math.sqrt(16);
Note: Math is not a constructor. All properties and methods of Math can be called by using Math as an object without creating it.

Mathematical Constants

JavaScript provides eight mathematical constants that can be accessed from the Math object. These are: E, PI, square root of 2, square root of 1/2, natural log of 2, natural log of 10, base-2 log of E, and base-10 log of E.
You may reference these constants from your JavaScript like this:
Math.E
Math.PI
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E


Mathematical Methods

In addition to the mathematical constants that can be accessed from the Math object there are also several methods available.
The following example uses the round() method of the Math object to round a number to the nearest integer:
document.write(Math.round(4.7));
The code above will result in the following output:
5
The following example uses the random() method of the Math object to return a random number between 0 and 1:
document.write(Math.random());
The code above can result in the following output:
0.27015238226521243
The following example uses the floor() and random() methods of the Math object to return a random number between 0 and 10:
document.write(Math.floor(Math.random()*11));
The code above can result in the following output:
3

JavaScript RegExp Object

What is RegExp?

A regular expression is an object that describes a pattern of characters.
When you search in a text, you can use a pattern to describe what you are searching for.
A simple pattern can be one single character.
A more complicated pattern can consist of more characters, and can be used for parsing, format checking, substitution and more.
Regular expressions are used to perform powerful pattern-matching and "search-and-replace" functions on text.

Syntax

var patt=new RegExp(pattern,modifiers);

or more simply:

var patt=/pattern/modifiers;
  • pattern specifies the pattern of an expression
  • modifiers specify if a search should be global, case-sensitive, etc.

RegExp Modifiers

Modifiers are used to perform case-insensitive and global searches.
The i modifier is used to perform case-insensitive matching.
The g modifier is used to perform a global match (find all matches rather than stopping after the first match).

Example 1

<html>
<body>

<script type="text/javascript">
var str = "Visit shibashish";
var patt1 = /shibashish/i;
document.write(str.match(patt1));
</script>

</body>
</html>


Do a case-insensitive search for "w3schools" in a string:
var str="Visit shibashish";
var patt1=/shibashish/i;
The marked text below shows where the expression gets a match:
Visit shibashish



Example 2

<html>
<body>

<script type="text/javascript">

var str="Is this all there is?";
var patt1=/is/g;
document.write(str.match(patt1));

</script>

</body>
</html>
Do a global search for "is":
var str="Is this all there is?";
var patt1=/is/g;
The marked text below shows where the expression gets a match:
Is this all there is?



Example 3

<html>
<body>

<script type="text/javascript">

var str="Is this all there is?";
var patt1=/is/gi;
document.write(str.match(patt1));

</script>

</body>
</html>

Do a global, case-insensitive search for "is":
var str="Is this all there is?";
var patt1=/is/gi;
The marked text below shows where the expression gets a match:
Is this all there is?




test()

The test() method searches a string for a specified value, and returns true or false, depending on the result.
The following example searches a string for the character "e":

Example

 <html>
<body>

<script type="text/javascript">
var patt1=new RegExp("e");

document.write(patt1.test("The best things in life are free"));
</script>

</body>
</html>
var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are free"));
Since there is an "e" in the string, the output of the code above will be:
true




exec()

The exec() method searches a string for a specified value, and returns the text of the found value. If no match is found, it returns null.
The following example searches a string for the character "e":

Example 1

 <html>
<body>

<script type="text/javascript">
var patt1=new RegExp("e");

document.write(patt1.exec("The best things in life are free"));
</script>

</body>
</html>
var patt1=new RegExp("e");
document.write(patt1.exec("The best things in life are free"));
Since there is an "e" in the string, the output of the code above will be:
e

JavaScript Browser Detection

The Navigator object contains information about the visitor's browser.

Browser Detection

Almost everything in this tutorial works on all JavaScript-enabled browsers. However, there are some things that just don't work on certain browsers - especially on older browsers.
Sometimes it can be useful to detect the visitor's browser, and then serve the appropriate information.
The Navigator object contains information about the visitor's browser name, version, and more.
Note Note: There is no public standard that applies to the navigator object, but all major browsers support it.

The Navigator Object

The Navigator object contains all information about the visitor's browser:

Example

<div id="example"></div>

<script type="text/javascript">

txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";

document.getElementById("example").innerHTML=txt;

</script>

Try it yourself »

 

JavaScript Cookies

A cookie is often used to identify a user.

What is a Cookie?

A cookie is a variable that is stored on the visitor's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With JavaScript, you can both create and retrieve cookie values.
Examples of cookies:
  • Name cookie - The first time a visitor arrives to your web page, he or she must fill in her/his name. The name is then stored in a cookie. Next time the visitor arrives at your page, he or she could get a welcome message like "Welcome John Doe!" The name is retrieved from the stored cookie
  • Password cookie - The first time a visitor arrives to your web page, he or she must fill in a password. The password is then stored in a cookie. Next time the visitor arrives at your page, the password is retrieved from the cookie
  • Date cookie - The first time a visitor arrives to your web page, the current date is stored in a cookie. Next time the visitor arrives at your page, he or she could get a message like "Your last visit was on Tuesday August 11, 2005!" The date is retrieved from the stored cookie

Create and Store a Cookie

In this example we will create a cookie that stores the name of a visitor. The first time a visitor arrives to the web page, he or she will be asked to  fill in her/his name. The name is then stored in a cookie. The next time the visitor arrives at the same page, he or she will get welcome message.
First, we create a function that stores the name of the visitor in a cookie variable:
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
The parameters of the function above hold the name of the cookie, the value of the cookie, and the number of days until the cookie expires.
In the function above we first convert the number of days to a valid date, then we add the number of days until the cookie should expire. After that we store the cookie name, cookie value and the expiration date in the document.cookie object.
Then, we create another function that returns a specified cookie:
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}
The function above makes an array to retrieve cookie names and values, then it checks if the specified cookie exists, and returns the cookie value.
Last, we create the function that displays a welcome message if the cookie is set, and if the cookie is not set it will display a prompt box, asking for the name of the user, and stores the username cookie for 365 days, by calling the setCookie function:
function checkCookie()
{
var username=getCookie("username");
  if (username!=null && username!="")
  {
  alert("Welcome again " + username);
  }
else
  {
  username=prompt("Please enter your name:","");
  if (username!=null && username!="")
    {
    setCookie("username",username,365);
    }
  }
}
All together now:

Example

<html>
<head>
<script type="text/javascript">
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
  {
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

function checkCookie()
{
var username=getCookie("username");
if (username!=null && username!="")
  {
  alert("Welcome again " + username);
  }
else
  {
  username=prompt("Please enter your name:","");
  if (username!=null && username!="")
    {
    setCookie("username",username,365);
    }
  }
}
</script>
</head>
<body onload="checkCookie()">
</body>
</html>

Try it yourself »

 

JavaScript Form Validation

JavaScript Form Validation

JavaScript can be used to validate data in HTML forms before sending off the content to a server.
Form data that typically are checked by a JavaScript could be:
  • has the user left required fields empty?
  • has the user entered a valid e-mail address?
  • has the user entered a valid date?
  • has the user entered text in a numeric field?

Required Fields

The function below checks if a field has been left empty. If the field is blank, an alert box alerts a message, the function returns false, and the form will not be submitted:
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
  {
  alert("First name must be filled out");
  return false;
  }
}
The function above could be called when a form is submitted:

Example

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

Try it yourself »


E-mail Validation

The function below checks if the content has the general syntax of an email.
This means that the input data must contain an @ sign and at least one dot (.). Also, the @ must not be the first character of the email address, and the last dot must be present after the @ sign, and minimum 2 characters before the end:
function validateForm()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
  {
  alert("Not a valid e-mail address");
  return false;
  }
}
The function above could be called when a form is submitted:

Example

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>

Try it yourself » 

JavaScript Timing Events

JavaScript Timing Events

With JavaScript, it is possible to execute some code after a specified time-interval. This is called timing events.
It's very easy to time events in JavaScript. The two key methods that are used are:
  • setTimeout() - executes a code some time in the future
  • clearTimeout() - cancels the setTimeout()
Note: The setTimeout() and clearTimeout() are both methods of the HTML DOM Window object.

The setTimeout() Method

Syntax

var t=setTimeout("javascript statement",milliseconds);
The setTimeout() method returns a value. In the syntax defined above, the value is stored in a variable called t. If you want to cancel the setTimeout() function, you can refer to it using the variable name.
The first parameter of setTimeout() can be a string of executable code, or a call to a function.
The second parameter indicates how many milliseconds from now you want to execute the first parameter.
Note: There are 1000 milliseconds in one second.

Example

When the button is clicked in the example below, an alert box will be displayed after 3 seconds.

Example

<html>
<head>
<script type="text/javascript">
function timeMsg()
{
var t=setTimeout("alertMsg()",3000);
}
function alertMsg()
{
alert("Hello");
}
</script>
</head>

<body>
<form>
<input type="button" value="Display alert box in 3 seconds"
onclick="timeMsg()" />
</form>
</body>
</html>

Try it yourself »

Example - Infinite Loop

To get a timer to work in an infinite loop, we must write a function that calls itself.
In the example below, when a button is clicked, the input field will start to count (for ever), starting at 0.
Notice that we also have a function that checks if the timer is already running, to avoid creating additional timers, if the button is pressed more than once:

Example

<html>
<head>
<script type="text/javascript">
var c=0;
var t;
var timer_is_on=0;

function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}

function doTimer()
{
if (!timer_is_on)
  {
  timer_is_on=1;
  timedCount();
  }
}
</script>
</head>

<body>
<form>
<input type="button" value="Start count!" onclick="doTimer()">
<input type="text" id="txt" />
</form>
</body>
</html>

Try it yourself »


The clearTimeout() Method

Syntax

clearTimeout(setTimeout_variable)

Example

The example below is the same as the "Infinite Loop" example above. The only difference is that we have now added a "Stop Count!" button that stops the timer:

Example

<html>
<head>
<script type="text/javascript">
var c=0;
var t;
var timer_is_on=0;

function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}

function doTimer()
{
if (!timer_is_on)
  {
  timer_is_on=1;
  timedCount();
  }
}

function stopCount()
{
clearTimeout(t);
timer_is_on=0;
}
</script>
</head>

<body>
<form>
<input type="button" value="Start count!" onclick="doTimer()">
<input type="text" id="txt">
<input type="button" value="Stop count!" onclick="stopCount()">
</form>
</body>
</html>

Try it yourself »


Examples

More Examples

Another simple timing
A clock created with a timing event

 

JavaScript Create Your Own Objects

Objects are useful to organize information.

Examples

Try it Yourself - Examples

Create a direct instance of an object
Create a template for an object

JavaScript Objects

Earlier in this tutorial we have seen that JavaScript has several built-in objects, like String, Date, Array, and more. In addition to these built-in objects, you can also create your own.
An object is just a special kind of data, with a collection of properties and methods.
Let's illustrate with an example: A person is an object. Properties are the values associated with the object. The persons' properties include name, height, weight, age, skin tone, eye color, etc. All persons have these properties, but the values of those properties will differ from person to person. Objects also have methods. Methods are the actions that can be performed on objects. The persons' methods could be eat(), sleep(), work(), play(), etc.

Properties

The syntax for accessing a property of an object is:
objName.propName
You can add properties to an object by simply giving it a value. Assume that the personObj already exists - you can give it properties named firstname, lastname, age, and eyecolor as follows:
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=30;
personObj.eyecolor="blue";

document.write(personObj.firstname);
The code above will generate the following output:
John

Methods

An object can also contain methods.
You can call a method with the following syntax:
objName.methodName()
Note: Parameters required for the method can be passed between the parentheses.
To call a method called sleep() for the personObj:
personObj.sleep();


Creating Your Own Objects

There are different ways to create a new object:
1. Create a direct instance of an object
The following code creates an new instance of an object, and adds four properties to it:
personObj=new Object();
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=50;
personObj.eyecolor="blue";
alternative syntax (using object literals):
personObj={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};
Adding a method to the personObj is also simple. The following code adds a method called eat() to the personObj:
personObj.eat=eat;
2. Create an object constructor
Create a function that construct objects:
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
Inside the function you need to assign things to this.propertyName. The reason for all the "this" stuff is that you're going to have more than one person at a time (which person you're dealing with must be clear). That's what "this" is: the instance of the object at hand.
Once you have the object constructor, you can create new instances of the object, like this:
var myFather=new person("John","Doe",50,"blue");
var myMother=new person("Sally","Rally",48,"green");
You can also add some methods to the person object. This is also done inside the function:
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;

this.newlastname=newlastname;
}
Note that methods are just functions attached to objects. Then we will have to write the newlastname() function:
function newlastname(new_lastname)
{
this.lastname=new_lastname;
}
The newlastname() function defines the person's new last name and assigns that to the person. JavaScript knows which person you're talking about by using "this.". So, now you can write: myMother.newlastname("Doe").

JavaScript Examples

Basic JavaScript Examples

Write to the Document with JavaScript
Change HTML elements with JavaScript
An external JavaScript
Examples explained

JavaScript Statements, Comments and Blocks

JavaScript statements.
JavaScript blocks.
Single line comments.
Multiple lines comments.
Single line comment to prevent execution.
Multiple lines comment to prevent execution.
Examples explained

JavaScript Variables

Declare a variable, assign a value to it, and display it
Examples explained

JavaScript Conditional If ... Else

If statement
If...else statement
Random link
Switch statement
Examples explained

JavaScript Popup Boxes

Alert box
Alert box with line breaks
Confirm box
Prompt box
Examples explained

JavaScript Functions

Call a function
Function with an argument
Function with an argument 2
Function that returns a value
Function with arguments, that returns a value
Examples explained

JavaScript Loops

For loop
Looping through HTML headers
While loop
Do While loop
Break a loop
Break and continue a loop
Use a for...in statement to loop through the elements of an object
Examples explained

JavaScript Events

Acting to the onclick event
Acting to the onmouseover event
Examples explained

JavaScript Error Handling

The try...catch statement
The try...catch statement with a confirm box
The onerror event
Examples explained

Advanced JavaScript Examples

Create a welcome cookie
Simple timing
Another simple timing
Timing event in an infinite loop
Timing event in an infinite loop - with a Stop button
A clock created with a timing event
Create a direct instance of an object
Create an object constructor

JavaScript Objects Examples

Examples of using the built-in JavaScript objects.

String Object

Return the length of a string
Style strings
Return the position of the first occurrence of a text in a string - indexOf()
Search for a text in a string and return the text if found - match()
Replace characters in a string - replace()
More String object examples in our JavaScript reference.

Date Object

Use Date() to return today's date and time
Use getTime() to calculate the years since 1970
Use setFullYear() to set a specific date
Use toUTCString() to convert today's date (according to UTC) to a string
Use getDay() and an array to write a weekday, and not just a number
Display a clock
More Date object examples in our JavaScript reference.

Array Object

Create an array
Join two arrays - concat()
Join three arrays - concat()
Join all elements of an array into a string - join()
Remove the last element of an array - pop()
Add new elements to the end of an array - push()
Reverse the order of the elements in an array - reverse()
Remove the first element of an array - shift()
Select elements from an array - slice()
Sort an array (alphabetically and ascending) - sort()
Sort numbers (numerically and ascending) - sort()
Sort numbers (numerically and descending) - sort()
Add an element to position 2 in an array - splice()
Convert an array to a string - toString()
Add new elements to the beginning of an array - unshift()
More Array object examples in our JavaScript reference.

Boolean Object

Check Boolean value
More Boolean object examples in our JavaScript reference.

Math Object

Use round() to round a number
Use random() to return a random number between 0 and 1
Use max() to return the number with the highest value of two specified numbers
Use min() to return the number with the lowest value of two specified numbers
Convert Celsius to Fahrenheit

JavaScript Browser Objects Examples

Examples of using JavaScript to access and manipulate the Browser objects.

Window Object

Display an alert box
Display an alert box with line-breaks
Display a confirm box, and alert what the visitor clicked
Display a prompt box
Create a pop-up window Open a new window when clicking on a button
Open a new window and control its appearance
Open multiple new windows
Assure that the new window does NOT get focus (send it to the background)
Assure that the new window GETS focus
Close the new window
Checks whether the new window has been closed or not
Return the name of the new window
Write some text to the source (parent) window
Move the new window relative to its current position
Move the new window to the specified position
Print the current page
Resize a window by the specified pixels
Resize a window to a specified size
Scroll the content by the specified number of pixels
Scroll the content to a specified position
A simple timing
Set and stop a timer with setTimeout() and clearTimeout()
Set and stop a timer with setInterval() and clearInterval()
More Window object examples in our JavaScript reference.

Navigator Object

All details about the visitor's browser
More Navigator object examples in our JavaScript reference.

Screen Object

All details about the visitor's screen
More Screen object examples in our JavaScript reference.

History Object

Return the number of URLs in the history list
Create a back button on a page
Create a forward button on a page
Load a specific URL from the history list
More History object examples in our JavaScript reference.

Location Object

Return the hostname and port of the current URL
Return the entire URL of the current page
Return the path name of the current URL
Return the protocol portion of the current URL
Load a new document
Reload the current document
Replace the current document
Break out of a frame

JavaScript HTML DOM Examples

Examples of using JavaScript to access and manipulate the HTML DOM objects.

Document Object

Write text to the output with document.write()
Write formatted text to the output with document.write()
Return the number of anchors in a document
Return the innerHTML of the first anchor in a document
Return the number of forms in a document
Return the name of the first form in a document
Return the number of images in a document
Return the id of the first image in a document
Return the number of links in a document
Return the id of the first link in a document
Return all name/value pairs of cookies in a document
Return the domain name of the server that loaded the document
Return the date and time the document was last modified
Return the URL of the document that loaded the current document
Return the title of a document
Return the full URL of a document
Open an output stream, and add some text
Open an output stream in a new window, and add some text
Difference between write() and writeln()
Alert innerHTML of an element with a specific ID
Alert the number of elements with a specific name
Alert the number of elements with a specific tagname
More Document object examples in our JavaScript reference.

Anchor Object

Return and set the value of the charset attribute of a link
Return the value of the href attribute of a link
Return and set the value of the hreflang attribute of a link
Return the name of an anchor
Return the relationship between the current document and the linked document
Change the target attribute of a link
Return the value of the type attribute of a link
More Anchor object examples in our JavaScript reference.

Area Object

Return the alternate text for an area in an image-map
Return the coordinates of an area in an image-map
Return the anchor part of the href attribute of an area
Return the hostname:port for an area in an image-map
Return the hostname for an area in an image-map
Return the port for an area in an image-map
Return the href of an area in an image-map
Return the pathname for an area in an image-map
Return the protocol for an area in an image-map
Return the querystring part of the href attribute of an area
Return the shape of an area in an image-map
Return the value of the target attribute for an area in an image-map
More Area object examples in our JavaScript reference.

Base Object

Return the base URL for all relative URLs on a page
Return the base target for all links on a page
More Base object examples in our JavaScript reference.

Button Object

Set a button to disabled when clicked
Return the name of a button
Return the type of a button
Return the text displayed on a button
Return the id of the form a button belongs to
More Button object examples in our JavaScript reference.

Form Object

Return the value of each element in a form
Return the value of the accept-charset attribute in a form
Return the value of the action attribute in a form
Return the value of the enctype attribute in a form
Return the number of elements in a form
Return the method for sending form data
Return the name of a form
Return the value of the target attribute in a form
Reset a form
Submit a form
More Form object examples in our JavaScript reference.

Frame/IFrame Objects

Align an iframe
Change the background color of the document contained in an iframe
Return the value of the frameborder attribute in an iframe
Remove frameborder of an iframe
Change the height and width of an iframe
Return the value of the longdesc attribute in an iframe
Return the value of the marginheight attribute in an iframe
Return the value of the marginwidth attribute in an iframe
Return the value of the name attribute in an iframe
Return and set the value of the scrolling attribute in an iframe
Change the src attribute of an iframe

More Frame/IFrame object examples in our JavaScript reference.

Image Object

Align an image
Return the alternate text of an image
Add border to an image
Change the height and width of an image
Set the hspace and vspace properties of an image
Return the value of the longdesc attribute of an image
Create a link to a low-resolution version of an image
Return the name of an image
Change the src of an image
Return the value of the usemap attribute of a client-side image-map

More Image object examples in our JavaScript reference.

Event Object

Which mouse button was clicked?
What is the keycode of the key pressed?
What are the coordinates of the cursor?
What are the coordinates of the cursor, relative to the screen?
Was the shift key pressed?
Which element was clicked?
Which event type occurred?

Option and Select Objects

Disable and enable a dropdown list
Get the id of the form that contains the dropdown list
Get the number of options in the dropdown list
Turn the dropdown list into a multiline list
Select multiple options in a dropdown list
Alert the selected option in a dropdown list
Alert the index of the selected option in a dropdown list
Change the text of the selected option
Remove options from a dropdown list

Table, TableHeader, TableRow, TableData Objects

Change the width of a table border
Change the cellPadding and cellSpacing of a table
Specify frames of a table
Specify rules for a table
InnerHTML of a row
InnerHTML of a cell
Create a caption for a table
Delete rows in a table
Add rows to a table
Add cells to a table row
Align the cell content in a table row
Vertical align the cell content in a table row
Align the cell content in a single cell
Vertical align the cell content in a single cell
Change the content of a table cell
Change the colspan of a table row

Thanks

shibashish mohanty


No comments:

Post a Comment

Please don't spam, spam comments is not allowed here.

.

ShibashishMnty
shibashish mohanty