java script basics

25
JavaScript Basics J avaScript is a scripting language that will allow you to add real programming to your webpages. JavaScript is lightweight programming language with object oriented capabilities. JavaScript is executed directly in the browser and all main browsers contain a compiler or interpreter for JavaScript. JavaScript is case sensitive. JavaScript and Java are completely different programming languages even though they have a similar name. You can put JavaScript into an external file or directly into the HTML page. If you put the JavaScript code into the HTML page you can either put it into the header or in the body of the HTML page. JavaScript which is embedded into an HTML page must be surrounded by <script type="text/javascript"> </script> tags. The type is mandatory, even if the browser only supports JavaScript. JavaScript in the body will be executed while the page loads. JavaScript in the header will be executed when other JavaScript functions in the body call them. JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs . The HTML Document Object Model (DOM) is the browser's view of an HTML page as an object hierarchy, starting with the browser window itself and moving deeper into the page, including all of the elements on the page and their attributes. Below is a simplified version of the HTML DOM.

Upload: thakur-amit-tomer

Post on 20-Aug-2015

109 views

Category:

Technology


4 download

TRANSCRIPT

JavaScript Basics

JavaScript is a scripting language that will allow you to add real programming to your webpages.

JavaScript is lightweight programming language with object oriented capabilities.

JavaScript is executed directly in the browser and all main browsers contain a compiler or interpreter for JavaScript. JavaScript is case sensitive. JavaScript and Java are completely different programming languages even though they have a similar name.

You can put JavaScript into an external file or directly into the HTML page. If you put the

JavaScript code into the HTML page you can either put it into the header or in the body of

the HTML page. JavaScript which is embedded into an HTML  page must be surrounded by

<script type="text/javascript"> </script> tags. The type is mandatory, even if the browser only

supports JavaScript.

JavaScript in the body will be executed while the page loads. JavaScript in the header will be

executed when other JavaScript functions in the body call them.

JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.

The HTML Document Object Model (DOM) is the browser's view of an HTML page as an object hierarchy, starting with the browser window itself and moving deeper into the page, including all of the elements on the page and their attributes. Below is a simplified version of the HTML DOM.

javascript: Pseudo-ProtocolThe javascript: prefix is called a pseudo-protocol, because it mimics the protocol syntax (e.g, like http:, ftp:, andmailto:). It provides an easy way to test JavaScript on a page. It can also be used in links .

If you paste javascript:alert("Hello world!"); in the location bar of your browser than you will get an alert saying hello world.

Variables:-

Variables defined without the keyword "var" are global variables. Variables defined with "var" are

scoped according to their declaration, e.g. if you define a "var" in a function this variable is only

valid in this function.

It is good JavaScript practice to always use the "var" keyword for defining a variable in

JavaScript.

JavaScript has five basic types, Object,Array and the primitive types Number, String, and

Boolean.

Arrays:-

Arrays are Objects in JavaScript. We can use pop () and push (newValue) method to remove and

value at the end of array.

Syntax 1  var myArray = new Array()

Syntax 2  var myArray = new Array(sizeInteger)Syntax 3  var myArray = new Array(element0, element1, ..., elementN)

An array is a grouping of objects that can be accessed through subscripts. At its simplest, an array can be thought of as a list. In JavaScript, the first element of an array is considered to be at position zero (0), the second element at position one (1), and so on. Arrays are useful for storing related sets of data.

Array Properties and Methods

The tables below show some of the most useful array properties

and methods. All of the examples assume an array

called beatles that holds "Paul", "John", "George", and "Ringo".var beatles = ["Paul", "John", "George", "Ringo"];

Array Properties

Propert

yDescription

length

Holds the number of elements in an

array.

beatles.length // 4

Array Methods

Property Description

join(delimiter)

Returns a delimited list of the items indexed with

integers in the array. The default delimiter is a

comma.

beatles.join(":") // Paul:John:George:Ringo

push()Appends an element to an array.

beatles.push("Steve")

pop()

Removes the last item in an array and returns its

value.

beatles.pop() // Returns Ringo

shift()

Removes the first item in an array and returns its

value.

beatles.shift() // Returns Paul

slice(start,

end)

Returns a subarray from start to end. If end is left

out, it includes the remainder of the array.

beatles.slice(1 ,2) //Returns [John, George]

splice(start,

count)

Removes count items from start in the array and

returns the resulting array.

beatles.splice(1, 2) //Returns [Paul, Ringo]

sort()

Sorts an array alphabetically.

beatles.sort() //Returns [George, John, Paul,

Ringo]

Functions:-

A function in JavaScript encapsulates reusable code and is represented as Objects. Functions

can be directly called via other JavaScript code. It is recommended that you put functions in the

header of the HTML page.

Functions are declared via the “function” keyword. You can call a function directly, or use the

apply method on the function.

Syntax:

var variablename = new Function(Arg1, Arg2..., "Function Body");

Global Functions

JavaScript has a number of global functions. We will examine some

of them in this section. These all global function are the function of

window object. but as window is assumed if no object is referenced,

we don't need to explicitly write window.parseFloat() or window.isNaN(). 

Number(object)

The Number() function takes one argument: an object, which it

attempts to convert to a number. If it cannot, it returns NaN, for "Not

a Number."

String(object)

The String() function takes one argument: an object, which it

converts to a string.

isNaN(object)

The isNaN() function takes one argument: an object. The function

checks if the object is not a number (or cannot be converted to a

number). It returns true if the object is not a number and false if it is

a number.

parseFloat() and parseInt()

The parseFloat() function takes one argument: a string. If the string

begins with a number, the function reads through the string until it

finds the end of the number, hacks off the remainder of the string,

and returns the result. If the string does not begin with a number,

the function returns NaN.

The parseInt() function also takes one argument: a string. If the

string begins with an integer, the function reads through the string

until it finds the end of the integer, hacks off the remainder of the

string, and returns the result. If the string does not begin with an

integer, the function returns NaN.

HTML Events:-

Events are actions that can be detected by JavaScript. 

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.

Table 1. Events in JavaScript

Event Description

Onload Triggered then the user loads the page. The onload even can for example

Event Description

be used to check the visitors browser type.

onChange Called whenever a field is changed. Can for example be used to

validate an input field of a form.

onSubmit Called then a user clicks on the submit button of a form.

OnMouseOver and OnMouseOut Called then the mouse enters a certain element on the page or leaves it.

onFocus, onblur and onchange are mainly used in combination with validation of form fields.

onload and onunload are mainly used for popups that appear when the user enters or leaves the page.

onsubmit is used for one major purpose: To validate all fields within a form before actually submitting it.

onmouseover and onmouseout are mainly used for one purpose: To create animated buttons.

The following are the most important events recognized by JavaScript:

Event Detected when HTML tags

onfocus="" Form field gets focus select, text, textarea

onblur="" Form field loses focus select, text, textarea

onchange="" Content of a field changes select, text, textarea

onselect="" Text is selected text, textarea

onmouseover="" Mouse moves over a link A

onmouseout="" Mouse moves out of a link A

onclick="" Mouse clicks an objectA, button, checkbox, radio, reset, submit

onload="" Page is finished loading body, frameset

onunload="" Browser opens new document body, frameset

onSubmit="" Submit button is clicked form

Event Applies to Occurs whenEvent

handler

abort images User aborts the loading of an image (for example by clicking a link or clicking the Stop button)

onAbort

blur windows, frames, and all form elements User removes input focus from window, frame, or form element

onBlur

click buttons, radio buttons, checkboxes, submit buttons, reset buttons, links

User clicks form element or link onClick

change text fields, textareas, select lists User changes value of element onChange

error images, windows The loading of a document or image causes an error

onError

focus windows, frames, and all form elements User gives input focus to window, frame, or form element

onFocus

load document body User loads the page in the Navigator

onLoad

mouseout areas, links User moves mouse pointer out of an area (client-side image map) or link

onMouseout

mouseover links User moves mouse pointer over a link

onMouse- Over

reset forms User resets a form (clicks a Reset button)

onReset

select text fields, textareas User selects form element's input onSelect

field

submit submit button User submits a form onSubmit

unload document body User exits the page onUnload

Event

HandlerElements Supported Description

onblura, area, button, input, label, select,

textarea

the element lost

the focus

onchange input, select, textarea

the element

value was

changed

onclick

All elements exceptapplet, base,

basefont, bdo, br, font, frame,

frameset, head, html, iframe, isindex,

meta, param, script, style, title

a pointer button

was clicked

ondblclick

All elements exceptapplet, base,

basefont, bdo, br, font, frame,

frameset, head, html, iframe, isindex,

meta, param, script, style, title

a pointer button

was double

clicked

onfocusa, area, button, input, label, select,

textarea

the element

received the

focus

onkeydown

All elements exceptapplet, base,

basefont, bdo, br, font, frame,

frameset, head, html, iframe, isindex,

meta, param, script, style, title

a key was

pressed down

onkeypress

All elements exceptapplet, base,

basefont, bdo, br, font, frame,

frameset, head, html, iframe, isindex,

meta, param, script, style, title

a key was

pressed and

released

Event

HandlerElements Supported Description

onkeyup

All elements exceptapplet, base,

basefont, bdo, br, font, frame,

frameset, head, html, iframe, isindex,

meta, param, script, style, title

a key was

released

onload frameset

all the frames

have been

loaded

onload bodythe document

has been loaded

onmousedow

n

All elements exceptapplet, base,

basefont, bdo, br, font, frame,

frameset, head, html, iframe, isindex,

meta, param, script, style, title

a pointer button

was pressed

down

onmousemov

e

All elements exceptapplet, base,

basefont, bdo, br, font, frame,

frameset, head, html, iframe, isindex,

meta, param, script, style, title

a pointer was

moved within

onmouseout

All elements exceptapplet, base,

basefont, bdo, br, font, frame,

frameset, head, html, iframe, isindex,

meta, param, script, style, title

a pointer was

moved away

onmouseove

r

All elements exceptapplet, base,

basefont, bdo, br, font, frame,

frameset, head, html, iframe, isindex,

meta, param, script, style, title

a pointer was

moved onto

onmouseup

All elements exceptapplet, base,

basefont, bdo, br, font, frame,

frameset, head, html, iframe, isindex,

meta, param, script, style, title

a pointer button

was released

onreset form the form was

Event

HandlerElements Supported Description

reset

onselect input, textareasome text was

selected

onsubmit formthe form was

submitted

onunload frameset

all the frames

have been

removed

onunload body

<noscript> Sorry...JavaScript is needed to go ahead.</noscript>

If users browser does not support JavaScript than the message inside <noscript> tag will be displayed in browser.

Window:- To open a new window follow this syntax.

var newWin = window.open(URL, name, features, replace);

All four parameters are options:

1. URL - the URL of the page to load. If it is left blank, a blank

window is open and can be written to

with newWin.document.write().

2. name - the target attribute of the window. This can be used to

reuse an existing window if it is open.

3. features - a comma-delimited list of window features. Some of

the most common are:

1. height - the height of the window

2. width - the width of the window

3. left - the left position of the window

4. top - the top position of the window

5. location - whether or not to include the location bar

6. menubar - whether or not to include the menubar

7. resizable - whether or not the window should be

resizable

8. scrollbars - whether or not to include scrollbars

9. status - whether or not to include the status bar

10. toolbar - whether or not to include the toolbar

4. replace - true or false. If set to true, the new page replaces the

current page (if there is one) in the browser window's history.

The height, width, left, and top features should be set in pixels.

The location, menubar, resizable, scrollbars, status,

and toolbar features are boolean values: "true" or "false", "yes" or

"no", or "1" or "0" will work.

Timers

Timers are started and stopped with the following four methods of

the window object:

1. setTimeout(code_to_execute, wait_time_in_milliseconds)

2. clearTimeout(timer)

3. setInterval(code_to_execute, interval_in_milliseconds)

4. clearInterval(interval)

Built-In JavaScript Objects:- Mostly used built-in object are String, Math and

Date.

String

Some common string properties and methods are shown below. In

all the examples, the variable webucator is the string "Webucator".

Common String Properties

Property Description

lengthRead-only value containing the number of characters

in the string.12

webucator.length//Returns 9

Common String Methods

Method Description

charAt(position)

Returns the character at the

specified position. Note that it is

zero-based, so the first letter in the

string is at position 0.12

webucator.charAt(4)//Returns c (the fifth character)

Common String Methods

Method Description

charCodeAt(position)

Returns the Unicode character code

of the character at the specified

position.

12

webucator.charCodeAt(4)//Returns 99

fromCharCode(characterCodes)

Returns the text representation of

the specified comma-delimited

character codes. Used

with String rather than a specific

String object.

12

String.fromCharCode(169)//Returns ©

indexOf(substring,startPositio

n)

Searches

from startPosition forsubstring.

Returns the position at which

thesubstring is found. If substring is

not found, returns -1.

12345

webucator.indexOf("cat");//Returns 4

webucator.indexOf("cat", 5);//Returns -1

Common String Methods

Method Description

lastIndexOf(substring,endPosit

ion)

Searches from the end of the string

forsubstring until endPosition is

reached. Returns the position at

which the substringis found.

If substring is not found, returns -1.

12345

webucator.lastIndexOf("cat");//Returns 4

webucator.lastIndexOf("cat", 5);//Returns 4

substring(startPosition,endPos

ition)

Returns the substring beginning

atstartPosition and ending with the

character

before endPosition. endPosition is

optional. If it is excluded, the

substring continues to the end of

the string.

12345

webucator.substring(4, 7);//Returns cat

webucator.substring(4);//Returns cator

Common String Methods

Method Description

substr(startPosition,length)

Returns the substring

of Length characters beginning

at startPosition. length is optional.

If it is excluded, the substring

continues to the end of the string.

12345

webucator.substr(4, 3);//Returns cat

webucator.substr(4);//Returns cator

slice(startPosition,endPositio

n)

Same assubstring(startPosition,

endPosition).

12

webucator.slice(4, 7);//Returns cat

slice(startPosition,positionFr

omEnd)

positionFromEnd is a negative

integer. Returns the substring

beginning atstartPosition and

ending positionFromEndcharacters

from the end of the string.

12

webucator.slice(4, -2);//Returns cat

Common String Methods

Method Description

split(delimiter)Returns an array by splitting a

string on the specified delimiter.

1234

var s = "A,B,C,D";var a = s.split(",");document.write(a[2]);//Returns C

toLowerCase()Returns the string in all lowercase

letters.

12

webucator.toLowerCase()//Returns webucator

toUpperCase()Returns the string in all uppercase

letters.

12

webucator.toUpperCase();//Returns WEBUCATOR

Math

The Math object is a built-in static object. The Math object's properties

and methods can be accessed directly (e.g, Math.PI) and are used for

performing complex math operations. Here are two commonly used

properties of the Math object.

Common Math Properties

Property Description

Math.PI Pi (Π)

1

2

Math.PI;

//3.141592653589793

Math.SQRT2 Square root of 2.

1

2

Math.SQRT2;

//1.4142135623730951

Below are some of the common Math methods that you can use to

perform mathematical operations:

Common Math Methods

Method Description

Math.abs(number) Absolute value of number.

1

2

Math.abs(-12);

//Returns 12

Math.ceil(number) number rounded up.

1 Math.ceil(5.4);

Common Math Methods

Method Description

2 //Returns 6

Math.floor(number) number rounded down.

1

2

Math.floor(5.6);

//Returns 5

Math.max(numbers) Highest Number in numbers.

1

2

Math.max(2, 5, 9, 3);

//Returns 9

Math.min(numbers) Lowest Number in numbers.

1

2

Math.min(2, 5, 9, 3);

//Returns 2

Math.pow(number, power) number to the power of power.

1

2

Math.pow(2, 5);

//Returns 32

Math.round(number) Rounded number.

1

2

Math.round(2.5);

//Returns 3

Math.random() Random number between 0 and 1.

1

2

3

Math.random();

//Returns random

//number from 0 to 1

You can see these examples in a browser by

openingBuiltInObjects/Demos/MathPropertiesAndMethods.html. In

the next activity, we'll use the Math.round() and Math.random()

methods in a simple example.

Method for Generating Random Integers

You can easily generate random numbers in JavaScript using

the Math.random()method.

1

2

3

4

5

var low = 1;

var high = 10;

var rndDec = Math.random();

var rndInt = Math.floor(rndDec * (high - low + 1) + low);

Date

The Date object has methods for manipulating dates and times. 

A few things to note:

1. To create a Date object containing the current date and time,

the Date()constructor takes no arguments.

2. When passing the date as a string to the Date() constructor,

the time portion is optional. If it is not included, it defaults to

00:00:00. Also, other date formats are acceptable (e.g,

"4/14/2011" and "14-04-2011").

3. When passing date parts to

the Date() constructor, dd, hh, mm, ss, and ms are all optional.

The default of each is 0.

4. Months are numbered from 0 (January) to 11 (December). 

5. Some common date methods are shown below. In all the

examples, the variablerightNow contains "Thu Apr 14

00:23:54:650 EDT 2011".

Common Date Methods

Method Description

getDate() Returns the day of the month (1-31).12

rightNow.getDate();//Returns 14

getDay()Returns the day of the week as a number (0-6,

0=Sunday, 6=Saturday).12

rightNow.getDay();//Returns 4

getMonth()Returns the month as a number (0-11, 0=January,

11=December).12

rightNow.getMonth();//Returns 3

getFullYear() Returns the four-digit year.12

rightNow.getFullYear();//Returns 2011

getHours() Returns the hour (0-23).12

rightNow.getHours();//Returns 0

getMinutes() Returns the minute (0-59).12

rightNow.getMinutes();//Returns 23

getSeconds() Returns the second (0-59).12

rightNow.getSeconds();//Returns 54

getMilliseconds

()Returns the millisecond (0-999).

12

rightNow.getMilliseconds();//Returns 650

Common Date Methods

Method Description

getTime()Returns the number of milliseconds since midnight

January 1, 1970.12

rightNow.getTime();//Returns 1113452634650

getTimezoneOffs

et()

Returns the time difference in minutes between

the user's computer and GMT.12

rightNow.getTimezoneOffset();//Returns 240

toLocaleString(

)Returns the Date object as a string.

123

rightNow.toLocaleString();//Returns Thursday, April 14,//2011 12:23:54 AM

toGMTString()Returns the Date object as a string in GMT

timezone.123

rightNow.toGMTString();//Returns Thu, 14 Apr 2011//04:23:54 UTC

typeof Operator

The typeof operator is used to find out the data type of a variable.

Experienced