Quantcast
Channel: DiKnows. » Uncategorized
Viewing all articles
Browse latest Browse all 10

JavaScript Article

$
0
0

Java Script
Hi every body,

may be that is the first time i write here at DiKnows.com but i hope that my article is being useful for that people who wants to learn about javascript
there are two kind of people who interisted in reading article like mine first one the people who want learn about java script then that article will be like overview for them to going on and start learn java script seriously second kind of people are programmers then i consider that article will be like a revision for what they are already know
let’s start:-
some people don’t know the defferent between javascript and java .. javascript or Ecmascript “JavaScript’s official name”  is a lightweight programming language which developed and maintained by the ECMA organization but java is a powerful and much more complex programming language which developed by Sun Microsystems . JavaScript is a scripting language gives HTML designers a programming tool .. it is usually embedded directly into HTML pages so if you want to learn java script you should have a basic understanding of HTML and XHTML

this is an example to how javascript is embed into an html page




the code above will make the browser write hello worled in the page

now if we want to write a javascript we can put it in the head section or the body section but if we want to prevent the browser from executing a script until an event happen in this case we put the javascript in function and put our functions code in the head section

usually we put the functions in the head and other code in body section

JavaScript is a sequence of statements to be executed by the browser .. Javascript statements is a command to a browser to tell the browser what to do

we put a semicolon ; at the end of the statement usually but if we didn’t write it that will be right too but with semicolon we can write many statement in one line

now if we wanted to add a comment to a script for Instruction purpose or restrict a script from execution we add // befor the line .. if we want to do that with more than one line we write /* at the first and */ at the end
an example


/* here we write the comment and below we prevent a script from execution */
//document.write("hello world”);

now we will talk about Variables .. if you remember the litters in algebra which hold a value to make some mathematic operations
the same thing in java script .. the variables is a litters which hold a value like numbers or litters .. that is an example :-

x=y+z
x,y,z a variables can hold value like that
x=2 , y=4 then we can get the value of z

variables could be a litter like x or a word you defind it but can’t be a number

when you creat a variable in javascript that called declaration and we make declaration by the word var like that

var x  or var someword

we can declare the variable without var by assign a value to the variable like that

someword=text

text is the value for the variable someword
when we assign a value to the variable this operation named definition

now after we talked about variables we can talk about how we can do operations with JavaScript variables by using the operators

for example we use = for assignment a value for a variable and we use + for adding a value to another

now we have five kinds of operators

1-arithmetic  operators
2-assignment  operators
3-comparison  operators
4-logical operators
5-conditional operators

the Schedule below explain the meaning of each operator

1- arithmetic operators Schedule :
we will consider that we have a variable x=3

the operator Description    Example  Result

+            Addition       y=x+1    y=4
-            Subtraction    y=x-1    y=2
*            Multiplication y=x*2    y=6
/            Division       y=x/2    y=1.5
%            Modulus        y=x%2    y=1
++           Increment      y=++x    y=4
--           Decrement      y=--x    y=2

note Modulus or % is division remainder and
The + operator can also be used to add string variables or text values together
like that

x=”hello”
y=” world”
z=x+y

After the execution of the statements above, the variable z contains(hello world)

2-assignment  operators Schedule :

if we have variables (x=4 , y=2) ;

Operator     Example     Same As     Result
=            x=y                     x=4
+=           x+=y        x=x+y       x=6
-=           x-=y        x=x-y       x=2
*=           x*=y        x=x*y       x=8
/=           x/=y        x=x/y       x=2
%=           x%=y        x=x%y       x=0

3-comparison  operators Schedule :

Operator      Description

==            is equal to
===           exactly equal to (value and type)
!=            	is not equal
>             is greater than
<             is less than
>=            is greater than or equal to
<=            is less than or equal to

for Example if we have variable x=10 ;

x==5			is false
x===10			is true
x==="10"		is false
x!=5			is true
x>5			is true
x<5			is false
x>=5			is true
x<=5			is false

4-logical operators Schedule :

Operator   Description

&&		and
||		or
!		not

for Example if we have variables (x=6,y=3) ;

(x < 10 && y > 1) is true
(x==5 || y==5) is false
!(x==y) is true

5-conditional operators :

conditional operator that assigns a value to a variable based on some condition
Example

greeting=(visitor==”PRES”)?”Dear President “:”Dear “;

If the variable visitor has the value of “PRES”, then the variable greeting will be assigned the value “Dear President ” else it will be assigned “Dear”

javascript has conditional statements which
we use to execute some code if a condition happend
we have four conditional statements in javascript

1-if statement : to execute a code only if    a specified condition is true
2-if…else statement : to execute a code     if the condition is true and another code   if the condition is false
3-if…else if…else statement : to          execute one of many blocks of code
4-switch statement : to execute one of many   blocks of code

examples

1-if statement :


/*browser will Write a "Good morning” greeting if the time is less than 10*/
var d=new Date();
var time=d.getHours();
/* this is an object to get the time we will explane it later*/
if (time<10){
	document.write("Good morning”);
}

2-if…else statement :


/*If the time is less than 10, you will get a "Good morning” greeting.Otherwise you will get a "Good day” greeting.*/

var d = new Date();
var time = d.getHours();

if (time < 10){
	document.write("Good morning!”);
}
else{
	document.write("Good day!”);
}

3-if…else if…else statement :


var d = new Date()
var time = d.getHours()
if (time < 10){
	document.write("Good morning”);
}
else if (time>10 && time < 16){
	document.write("Good day”);
}
else{
	document.write("Hello World!”);
}

4-switch statement :


/*You will receive a different greeting based on what day it is. Note that Sunday=0, Monday=1, Tuesday=2, etc.*/

var d=new Date();
theDay=d.getDay();
switch (theDay){
	case 5:
		document.write("Finally Friday”);
	break;
	case 6:
		document.write("Super Saturday”);
	break;
	case 0:
		document.write("Sleepy Sunday”);
	break;
	default:
		document.write("I’m looking forward to this weekend!”);
}

now we will talk about popup boxes , javascript has three kind of popup boxes :

1-Alert box
2-Confirm box
3-Prompt box

1-Alert box :
alert box is often used if you want to make sure information comes through to the user
,When an alert box pops up, the user will have to click “OK” to proceed

Example :


//we will explane how function works later
function show_alert(){
	alert("this is an alert box!”);
}

<input type=”button” onclick=”show_alert()” value=”Show alert box” />

2-Confirm box :
A confirm box is often used if you want the user to verify or accept something
When a confirm box pops up, the user will have to click either “OK” or “Cancel” to proceed.
If the user clicks “OK”, the box returns true. If the user clicks “Cancel”, the box returns false

Example :


function show_confirm(){
	var r=confirm("Press a button”);
	if (r==true){
		alert("You pressed OK!”);
	}
	else{
		alert("You pressed Cancel!”);
	}
}

<input type=”button” onclick=”show_confirm()” value=”Show confirm box” />

3-Prompt box :
A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either “OK” or “Cancel” to proceed after entering an input value.
If the user clicks “OK” the box returns the input value. If the user clicks “Cancel” the box returns null.

Example :

<script type=”text/javascript”>
function show_prompt(){
var name=prompt(“Please enter your name”,”Harry Potter”);
if (name!=null && name!=”"){
document.write(“Hello ” + name + “! How are you today?”);
}
}


<input type="button" onclick="show_prompt()" value="Show prompt box" />

now if we want to execute a script only when an event happen or when we call it then we put it in a function , the syntax will be like that


function functionname(var1,var2,...,varX){
    some code
}

example :


function displaymessage(){
	alert("Hello World!");
}

<input type="button" value="Click me!" onclick="displaymessage()" />

we can put function in header or body but to be more organized we put all functions in head section and other scripts in body section

JavaScript Loops :

Loops execute a block of code a specified number of times, or while a specified condition is true
JavaScript, has two different kind of loops


1-for loop
2-while loop

for   – loops through a block of code a             specified number of times
while – loops through a block of code while         a specified condition is true

example 1 :


/* i declared automatically like we type   var i=0;*/
for (i=0;i<=5;i++){
	/*i++ to increase i value by one number to get the end value for i which it 5*/
	document.write("The number is " + i);
	document.write("<br />");
}
/* we type document.write("<br />"); to go to the next line */

the browser will type

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

example 2 :


var i=0;
while (i<=5)
{
document.write("The number is " + i);
document.write("<br />");
i++;
}

the browser will type

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

example 3 :

The do…while Loop


var i=0;
do{
	document.write("The number is " + i);
	document.write("<br />");
	i++;
}
while (i<=5);

here in do .. while loop is exactly the same result like while loop but the different is even if the condition is false if we consider that i will never be less than or equal to 5 the browser will execute the script and type the first value of i

The break and continue statements :

The break statement will break the loop and continue executing the code that follows after the loop ,but continue statement will break in a part of the loop and continue the loop after that ,

example 1 :


var i=0;
for (i=0;i<=10;i++){
	if (i==3){
		break;
	}
	document.write("The number is " + i);
	document.write("<br />");
}

the browser will type

The number is 0
The number is 1
The number is 2

example 2 :


var i=0
for (i=0;i<=10;i++){
	if (i==3){
		continue;
	}
	document.write("The number is " + i);
	document.write("<br />");
}

the browser will type

The number is 0
The number is 1
The number is 2
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

Every element on a web page has certain events which can trigger a JavaScript we usually use event to execute a function ,we have a lot of event in javascript like :

onLoad and onUnload events are triggered when the user enters or leaves the page
,onFocus, onBlur and onChange events are often used in combination with validation of form fields ,onSubmit event is used to validate ALL form fields before submitting it ,onMouseOver and onMouseOut are often used to create “animated” buttons ;

example :


<img src="image_w3default.gif" name="mousetest" onMouseOver="document.images['mousetest'].src='image_w3default2.gif'"
onMouseOut="document.images['mousetest'].src='image_w3default.gif'" width="234" height="91" />

the browser will put an image will change when the mouse will move over it

if we want to test a block of code for errors we will use The try…catch statement like that :


var txt="";
function message(){
	try{
		alert("Welcome guest!");
	}
	catch(err)
	{
		txt="There was an error on this page.\n\n";
		txt+="Error description: " + err.description + "\n\n";
		txt+="Click OK to continue.\n\n";
		alert(txt);
	}
}

<input type="button" value="View message" onclick="message()" />

the code above has a typo in the alert in message() function it typed adddlert there is an alert box will appear when you click the button says :

There was an error on this page.

Error description: undefined

Click OK to continue.

The throw statement allows you to create an exception. If you use this statement together with the try…catch statement, you can control program flow and generate accurate error messages.

example :

 
var x=prompt("Enter a number between 0 and 10:","");
try{
	if(x>10){
		throw "Err1";
	}else if(x<0){
		throw "Err2";
	}else if(isNaN(x)){
		throw "Err3";
	}
}catch(er){
	if(er=="Err1"){
		alert("Error! The value is too high");
	}
	if(er=="Err2"){
		alert("Error! The value is too low");
	}
	if(er=="Err3") {
		alert("Error! The value is not a number");
	}
}

In JavaScript you can add special characters to a text string by using the backslash sign
The backslash (\) is used to insert apostrophes, new lines, quotes, and other special characters into a text string

The table below lists special characters that can be added to a text string with the backslash sign:

Code         Outputs

\'           single quote
\"           double quote
\&           ampersand
\\           backslash
\n           new line
\r           carriage return
\t           tab
\b           backspace
\f           form feed

example in code :

document.write (“You \& I are singing!”);

the browser will type

You & I are singing!

JavaScript ignores extra spaces , if you want your script more readable you can insert a white space like that

x = 2  it is same as x=2

and you can also break up the code line by using backslash \ like that


document.write"hello \ world"

the browser will write hello world without backslash

objects in javascript
object is special kind of data , JavaScript as an Object Oriented Programming (OOP) language has two kind of objects , first one is built-in objects , second one the object you can create by yourself..
Any object has properties and methods,
Properties are values associated with an object , but methods are actions can be performed on objects ..
here an examples for built-in objects :
length property for the string object it will return the number of characters to string object :


var x="hi all!";
document.write(x.length);

the browser will write 7 “the number of characters (hi all!)”

example for toUpperCase() method ,it will write the text in uppercase letters


var x="hi all!";
document.write(x.toUpperCase());

the browser will write HI ALL!

note : javascript is case sensitive that mean variable named “x” is not the same as “X” and the method “toUpperCase” not the same as “touppercase” ..

(x.toUpperCase()) here is a string object ,var x=”hi all!”; is string object too ,the string object is used to manipulate a stored piece of text like “hi all!”

Date object :
Date object deals with date and time ,for example we can use setFullYear() method to set a specific date like that :


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

There are four ways of instantiating a date:
1- new Date() // current date and time
2- new Date(milliseconds) //milliseconds       since 1970/01/01
3- new Date(dateString)
4- new Date(year, month, day, hours,           minutes, seconds, milliseconds)

Most parameters above are optional

Some examples of instantiating a date :


today = new Date()
d1 = new Date("October 13, 1975 11:13:00")
d2 = new Date(79,5,24)
d3 = new Date(79,5,24,11,33,0)

Array object :
array object is a variable hold many values
,we use the array object to store multiple values in a single variable

if we have a list of items like a thousand employee name and we want to put them into a variables to deal with them it will be on thousand different variable name like that


var employee1="roy"
var employee2="bin"
var employee3="alex"

etc..

what if we want to loop through the employees and find a specific one , the array can hold all variables values in a single variable to make that easy like  that :


var employee=new Array();
employee[0]="roy";
employee[1]="bin";
employee[2]="alex";

if we want to access the array we type the array name and the index number which start with 0 like that :


document.write(employee[1]);

the browser will type bin..

there are two more ways to create arrays


1- var employee=new Arry("roy","bin","alex")
2- var employee=["roy","bin","alex"]

Boolean object :
Boolean object return two values true or false ..
If the Boolean object has no initial value or if it is 0, -0, null, “”, false, undefined, or NaN, the object is set to false. Otherwise it is true (even with the string “false”)

that how we create a Boolean object


var myBoolean=new Boolean();

here some example to how boolean object return false


var myBoolean=new Boolean();
var myBoolean=new Boolean(0);
var myBoolean=new Boolean(null);
var myBoolean=new Boolean("");
var myBoolean=new Boolean(false);
var myBoolean=new Boolean(NaN);

the browser will type false every time

Math Object :
if we want to do a mathematical tasks in javascript we use Math Object which has 8 mathematical constants”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”

it will be like this in the script


Math.E
Math.PI
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E

Note: Math is not a constructor ,All properties and methods of Math can be called by using Math as an object without creating it

regular expression object :

when we search in a text we can use a pattern to describe what we are searching for ,Regular expressions are used to perform powerful pattern-matching and “search-and-replace” functions on text ,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

how we type the regular expression object,
there is two ways to type it


1- var txt=new RegExp(pattern,modifiers);
2- var txt=/pattern/modifiers;

Modifiers performs case-insensitive and global searches

example 1 :


var site = "DiKnows is my favorite site";
var patt1 = /DiKnows/i;
/*DiKnows here is a pattern and i is a modifier which make the matching is case-insensitive*/
document.write(str.match(patt1));

the browser will type DiKnows

example 2 :


var site = "DiKnows is my favorite site";
var patt1 = /s/g;
/*DiKnows here is a pattern and g is a modifier which make the matching is global it will find all matches rather than stopping after the first match*/
document.write(str.match(patt1));

the browser will type s,s if we want to get the capital S in search result we type gi in modifiers section then the browser will type S,s,s because we added the modifier i
which make the matching case-insensitive

The Navigator Object :

sometimes we want to know the browser’s name, version, Cookies Enabled or not, the Platform of your system and more, because some browsers deal with data with different way than other browsers, so if we defined the information about the client’s browser we will define the suitable data the browser will deal with

the Navigator object contains all information about the visitor’s browser which we need to define the suitable data to the browser

example :


document.write("Browser CodeName: " + navigator.appCodeName);
document.write("<br /><br />");
document.write("Browser Name: " + navigator.appName);
document.write("<br /><br />");
document.write("Browser Version: " + navigator.appVersion);
document.write("<br /><br />");
document.write("Cookies Enabled: " + navigator.cookieEnabled);
document.write("<br /><br />");
document.write("Platform: " + navigator.platform);
document.write("<br /><br />");
document.write("User-agent header: " + navigator.userAgent);

the browser here will type the information depending on my browser status like that :

Browser CodeName: Mozilla

Browser Name: Netscape

Browser Version: 5.0 (Windows; en-US)

Cookies Enabled: true

Platform: Win32

User-agent header: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2

now if we created a web site like a forum, and as we know the forum will ask the visitor about the username and password, sometimes we store the username and password in cookies to let the visitor login the next time without typing the username and password again ,

A cookie is often used to identify a user it 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.

now we will explane an example to storing a data like username by creating a cookie and store the name in it, that will give the user welcome message when he/she visite the page next time, First, we create a function that stores the name of the visitor in a cookie variable ,


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

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

Then, we create another function that checks if the cookie has been set


function getCookie(c_name){
	if (document.cookie.length > 0){
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1){
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return "";
}

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


function checkCookie(){
	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);
		}
	}
}

sometimes we want to validate data which user fill in to a registration form like if the user left required fields empty, if entered a valid e-mail address or not,if  entered a valid date or not, if entered text in a numeric field, and more
javascript can validate all these data before it send to the server and notify the user to correct it if it was false

The function below checks if the content has the general syntax of an email

This means that the input data must contain at least an @ sign and a dot (.), Also, the @ must not be the first character of the email address, and the last dot must at least be one character after the @ sign , it will be like that :


function validate_email(field,alerttxt){
	with (field) {
		apos=value.indexOf("@");
		dotpos=value.lastIndexOf(".");
		if (apos<1||dotpos-apos<2){
			alert(alerttxt);return false;
		}
		else {return true;}
	}
}

function validate_form(thisform){
	with (thisform){
		if (validate_email(email,"Not a valid e-mail address!")==false)
		{email.focus();return false;}
	}
}

<form action="submit.htm" onsubmit="return validate_form(this);" method="post">
Email: <input type="text" name="email" size="30">
<input type="submit" value="Submit">
</form>

we can create animated images with javascript by using functions and events,
in the following example we will add an image that should act as a link button on a web page. We will then add an onMouseOver event and an onMouseOut event that will run two JavaScript functions that will change between two images


function mouseOver(){
	document.getElementById("b1").src ="image1.gif";
}
function mouseOut(){
	document.getElementById("b1").src ="image2.gif";
}

<a href="http://www.DiKnows.com" target="_blank">
<img border="0" alt="Visit DiKnows!" src="image2.gif" id="b1"
onmouseover="mouseOver()" onmouseout="mouseOut()" /></a>

now if we want to execute a script after a period of time we can use timing event, timing event has two methods, setTimeout() method and clearTimeout() method, setTimeout() – executes a code some time in the future, clearTimeout() – cancels the setTimeout()
the syntax of setTimeout() Method will be like that

var t=setTimeout(“javascript statement”,milliseconds);

The setTimeout() method returns a value – In the statement above, the value is stored in a variable called t. If we want to cancel this setTimeout(), we can refer to it using the variable name.

The first parameter of setTimeout() is a string that contains a JavaScript statement. This statement could be a statement like “alert(’5 seconds!’)” or a call to a function, like “alertMsg()”.

The second parameter indicates how many milliseconds from now you want to execute the first parameter

Example


/*this function will display an alert box after 3 seconds*/
function timedMsg(){
	var t=setTimeout("alert('I am displayed after 3 seconds!')",3000);
}


<form>
<input type="button" value="Display alert box!" onClick="timedMsg()" />
<!--the code above will create a button will type on it Display alert box! when we click it it will run the function timedMsg()-->
</form>

we talked before about built in objects, now we will talk about the object you can build by yourself, there is two ways you can build object with,

1-Create a direct instance of an object
2-Create a template of an object

we will talk about first way, as we know the object have properties and methods, if we consider 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.

this example explane how we criate a direct instance of an object


personObj=new Object();
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=50;
personObj.eyecolor="blue";

note : we can add properties to an object by simply giving it a value

if we added


document.write(personObj.firstname);

to the script, the browser will write

John


Viewing all articles
Browse latest Browse all 10

Trending Articles