Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 8

UNIT – 2

Introduction to JavaScript
1. JavaScript originates from a language called Live Script. The idea was to find a
Language that can be used at client side, but not complicated as Java. JavaScript is a
simple language, which is only suitable for simple tasks.
2. A numbers of technologies are present that develops the static web page, but we
require language that is dynamic in nature to develop web pages on client side.
3. Dynamic HTML is a combination of content formatted using HTML, cascading style
sheets, a scripting language and DOM.
4. JavaScript program contains variables, objects and functions.
5. Each line is terminated by a semicolon. Curly brackets must surround blocks of code.
6. Functions have parameters, which are passed inside parenthesis
6. Variables are declared using the keyword var.
7. Script does not require main function and exit condition.
8. Java script starts with “<script language=”java script”>” tag and ends with “</script>”.
8. JavaScript code resembles the code of C language, the syntax of both the language is
very close to each other. The set of tokens and constructs are same in both the language.
9. DHTML pages responds to users actions.

Benefits of JavaScript
1. It is widely supported in browser
2. It gives easy access to document object and can manipulate most of them.
3. JavaScript can give interesting animations with many multimedia data types.
4. Special plug-in is not required to use JavaScript.
5. JavaScript is secure language.

1. Write a DHTM / JavaScript program that use variables, data types and functions.
<Html>
<Head><title>DHTML</title></head>
<script language="javascript">
function add()
{
var a,b,sum;
a=parseInt(document.f1.n1.value);
b=parseInt(document.f1.n2.value);
sum=a+b;
document.f1.n3.value=sum;
}
</script>
<body>
<form Name="f1">
Enter first integer <br><input name="n1" type="text"><br>
Enter second integer<br><input name="n2" type="text"><br>
Sum of two numbers <br><input name="n3" type="text"></br></br>
<input type="button" value=" add " ONCLICK="add()">
<input name="n4" type="reset" value="reset" ></br>
</form>
</body>
</html>

Objects in JavaScript
JavaScript is not a pure object oriented programming language, but uses the concept of
objects. The new keyword used here is to create an object, it allocates memory and
storage. Objects can have functions and variables. To differentiate between global
variables and those, which are part of an object but may have the same name, JavaScript
uses this keyword. When referring to a property of an object, whether a method or a
variable, a dot is placed between the object name and the property.

Note
1. Programming languages are of two kinds. They were
a. Object oriented (Example java).
b. Object Based (Example java Script).
2. Object is a real world thing or entity.
3. Object has state, behavior and identity.
4. State represents current state of an object, behavior indicates what actions are
performed with that object and identity gives unique identification or name for the object.
5. Objects are classified into two types. They were
a. Predefined objects.
b. User defined objects.
6. Java script-programming language is known as object-based programming language.
7. An attribute gives the properties of an object.
8. Object methods give behavior of the object.
9. Methods, attributes of an object are called with dot operator.
i.e. Object name. Method name (parameters);
i.e Object name. Attribute name;

Java script built Object purpose


in objects
Document To get complete control on document along with displaying contents.
Window To get dialog control and provision for accepting data from user.
Math Used for mathematical functions and standard constants in
mathematics
String String manipulation can be done and also include to generate html
mark up methods.
Date For date manipulation, mainly to get current date and time.
Number To get number constants.
Boolean Wrapper class for Boolean type.
Navigator Used to obtain browser information.
Screen Used to known the screen width and height.
Document object
1. A document is a web page that is being either displayed or created.
2. It is used to create Html pages using JavaScript. Using the write or writeln methods of
the document object does this.
Document. Write (“<body>”);
Document. Write (“<h1> Hello </h1>”);
3. Document. Form name. Textbox name. Value;

Method Name Purpose Common Usage


Write (string) Used write on the document Document. Write (“hai”);
without new line.
Writeln (string) Used write on the document with Document. Writeln (“hai”);
new line.

Window Object
It is used to open a window, close a window, get input from the user and display output to
the user.
Method Name Purpose Common Usage
Open (“URL”) Used to open a window. Window. Open (“C:\”);
Close () Used to close a window. Window. Close ();
Alert (“message”) Used to display text Window. Alert (“hai”);
Prompt (String) Used to enter data. Window. Prompt (“enter data”);
Status (“string”) Used to display text on Window. Status (“hai”);
status bar.
SetInterval(“fun”,sec) Used to call a function based T=Window.SetInterval (“a ()”,10)
on interval.
clearTimeOut(t1) Used to stop a function call Window. ClearTimeOut (T)

Math object
It is used for manipulation of numbers and to perform many common mathematical
calculations.
Rounding and Truncation Functions
Method Name Purpose Common Usage
Ceil (X) Gives nearest integer, which is not less Math. Ceil (5.5) is 6
than X. (Ceiling value.) Math. Ceil (5.0001) is 6
Math. Ceil (-9.9) is -9
Floor (X) Gives nearest integer, which is not greater Math. Floor (5.8) is 5
than X. (Flooring value.) Math. Floor (5.0001) is5
Math. Floor (-9.9) is –10

Comparison Functions
Method Name Purpose Common Usage
Max (X, Y) Gives maximum value from x and y Math. Max (10,40) is 40.
Min (X, Y) Gives minimum value from x and y Math. Min (10,40) is 10
Miscellaneous Functions
Method Name Purpose Common Usage
Abs (X) Returns the absolute value. Math. Abs (-40) is 40
Math. Abs (50) is 50
Sqrt (X) Gives square root of X. Math. sqrt (9.0) is 3.0
Random (X) Generates a random number in between 0 Math. random (9.0) is
and 1. 3.0

Logarithm Related Functions


Method Name Purpose Common Usage
Log (X) Gives natural logarithm or base of X. Math. Log (--)
Exp (X) Gives exponential of given number. Math. Exp (X)
Pow (Base, Exp) Gives power value for base to the Math. Pow (3,2) is 9
exponential. Exp raised to base (Base exp)

Trigonometric Functions (Note: X is in radians not in degrees)


Method Name Purpose Common Usage
Sin (X) Returns sin value of X. Math. sin (0.0) is 0.0
Cos (X) Returns cosine value of X. Math. cos (0.0) is 1.0
Tan (X) Return tangent value of X.
Asin (X) Returns arc sin value of X. (sine inverse). Math. Asin()
Acos (X) Returns arc cosine value of X. (cosine Math. Acos()
inverse).
Atan (X) Returns arc tangent value of X. (tan inverse). Math. Atan()
Atan 2(X) Returns the angle of the polar coordinate that Math. Atan2()
corresponds to the passed x, y coordinates.

Constant Description
Math. E Euler’s constant.
Math.LN2 Natural logarithm of 2.
Math.LN10 Natural logarithm of 10.
Math.LOG2E Base 2 logarithm of Euler’s constant.
Math.LOG10E Base 10 logarithm of Euler’s constant.
Math. PI Pi value that is result of 22 / 7.
Math.SQRT1_2 Square root of ½ (0.5).
Math.SQRT2 Square root of 2.
String Object
1. A string is a collection of characters (special characters, digits and white spaces e.t.c).
2. String object is used to work with the strings.
3. Strings may be written with the help of single or double quotation marks.
4. String itself treated as an object called as string object.
Conversion Methods
Method Name Description
to LowerCase (); To convert to lower case.
toUpperCase (); To convert to upper case.
fromCharChode(v1, v2,..) Converts given Unicode .
toString() Converts to string.

Searching Methods
Method Name Description
charAt (position) Return character at given position.
charCodeAt (position) Returns character code at given position.
indexOf (string) Finds the position of string in any string from starting position.
indexOf (string, n) Finds the position of string in any string from given offset n.
lastIndexOf (String) Finds the position of string in any string from last occurrence,
start from end of any string.
lastIndexOf (String, n) Finds the position of string in any string from last occurrence,
start from position index and search towards beginning.

Obtain String Methods


Method Name Description
subStr (m, n) Extract n characters from m-th position.
subString(m, n) Extract characters from m to n, but not including n-th character.
Split(delim) Splits the string in to array of strings accordingly to given
delimiter.

HTML Markup Tags For String Methods


Method Name Description
Big To display string <BIG> text.
Blink() To display string <BLINK> text.
Bold() To display string <BOLD> text.
Italics To display string <ITALICS> text.
Small() To display string <SMALL> text.
Strike() To display string <strike> text.
Sub To display string <sub> text.
Sup To display string <sup> text.
Link(“address”) Used for <A HREF=”address” >tag
Anchor(“string”) Used for <A NAME=”string” >Tag
Date object
JavaScript provides functions to perform many different date manipulations. Some of the
functions are mentioned below.

Method or Means
constructor
Date() Construct an empty date object.
Date(year, month, Create a new Date object based upon numerical values for the year,
day [,hour, minute, month and
second]) day. Optional time values may also be supplied.
getDate( ) Return the day of the month
getDay( ) Return an integer representing the day of the week.
getFullYear( ) Return the year as a four digit number.
getHours( ) Return the hour field of the Date object.
getMinutes( ) Return the minutes field of the Date object.
getSeconds( ) Return the second field of the Date object.
setDate(day ) Set the day value of the object. Accepts values in the range 1 to 31.
setFullYear( year Set the year value of the object. Optionally also sets month and day
[,month, day]) values.
toString( ) Returns the Date as a string.

Number object
1. It is used for any number type and is a wrapper object in java script.
Example:-
Var n=new number (1234.1919);
2. Number objects properties.
a. Number name. MAX_Value b. Number name. MIN_Value
c. Number name. NAN. d. Number name.NEGITIVE_INFINITY.
e. Number name. POSITIVE_INFINITY.

Boolean object
1. Wrapper object for Boolean data type is Boolean object.
Example:-
Var n=new Boolean (1234.1919);
2. It accepts parameters true, false, 0, 1 number.
3. If it empty string or number. Nan it treats as false values.

Boolean Objects Methods


Method Name Purpose
toString() To convert to String for true or false values.
valueOf() To get value of Boolean object.

Navigator object
It is used to obtain browsers information.
Example: - Navigator.userAgent
Property Purpose
appCodeName The internal name for the browser.
appName Application Name.
appVersion Application Version.
Language Default language of browser.
Platform The Os the browser is running under.
SystemLanguage Default language of underlying system.
UserAgent HTTP user –agent value.
UserLanguage Language of current user.
Plugins[] An array of installed plug ins.

Regular Expression
A scripting language is to create a pattern called a regular expression, which describes a
set of characters that may be present in a string.

var pattern = new RegExp(“target”);


var string = “can you find the target”;
pattern.exec(string); //Regular expression is a javascript object.
Dynamic patterns are created using the Keyword new.
regex = new RegExp(“feroz | amer”);

Events: -
JavaScript is a event-driven system. Nothing happens unless it is initiated by an event
outside the script. The table below shows event, event handler and the description about
the event handler.
Event Handler Description
Blur onBlur The input focus is moved from the object, usually when
moving from a field of a form or from the form itself.
Change onChange The value of a field in a form has been changed by the
entering or deleting data.
Click onClick The mouse is clicked over an element of a page.
Double click onDblClick A form element / link is clicked twice in rapid succession.
Focus onFocus Input focus is given to an element. The reverse of blur
Key down onKeyDown A key is pressed but not released.
Key press onKeyPress A key is pressed.
Key up onKeyUp A pressed key is released
Load onLoad The page is loaded by the browser
Mouse down onMouseDown A mouse button is pressed
Mouse move onMouseMove The mouse is moved
Mouse out onMouseOut The mouse pointer moves off an element
Mouse over onMouseOver The mouser pointer moved over an element
Move onMove A window is moved
Resize onResize A window is resized
Submit onSubmit A form is submitted.
Unload onUnload The user leaves the web page.
Screen Properties
Property Purpose
WIDTH Gives the width value of current screen.
HEIGHT Gives the height value of current screen.

Dynamic HTML with JavaScript


1. DHTML page is one, which responds to user actions and gives response.
i.e It takes input (Request) from user and process input and give output (Response).
2. It is used for Data Validation.Data validation is the common process that takes place in
the web sites. Common request is for a way of validating the username and password.

1. Write a JavaScript program for data validation.


Myform.html
<Html>
<Head>
<script language = "javascript" src="validate.js">
</script>
</head>
<Body>
<form name="abcd">
Background Color: < input type="text" name="bg" value="white">
Candidate's name :< input type="text” name="c">
<input type="button" value="showit" onClick="valid()">
</form>
</body>
</html>

Validate.js
function valid()
{
var t1=document.abcd.bg.value;
var t2=document.abcd.c.value;
document.write("<body bgcolor="+t1+">");
document.write(t2);
}

You might also like