JavaScript is a programming language that is used to make web pages interactive. It runs on your visitor's computer and so does not require constant downloads from your web site.JavaScript was originally developed by Netscape Corporation for use in its browser, Netscape Navigator. It includes a convenient syntax, flexible variable types, and easy access to the browser's features. It can run on the browser without being compiled; the source code can be placed directly into a Web page. JavaScript will attempt to execute the commands within the <SCRIPT> and </SCRIPT> tag if there is no LANGUAGE attribute, or if the LANGUAGE attribute is set to JavaScript; in addition, the LANGUAGE attribute also can be used to distinguish between various versions of JavaScript.
Difference between java and javascript
JavaScript | Java |
Interpreted by client | Compiled by the author, run on client |
Code integrated in HTML documents | Applets distinct from HTML document |
Loose typing of data types | Strong typing of data types |
Script limited to browser functions | Stand-alone applications |
Works with HTML elements | Goes beyond HTML (for example, multimedia) |
Access browser objects and functionality | No access to browser functionality objects |
Uses of JavaScript
The most important uses for JavaScript are: -
- Dynamic forms that include built-in error checking
- Calculation areas on pages
- User interaction for warnings and getting confirmation
- Dynamically changing background and text colours, or "buttons".
- To look at the URL history and take action based on it.
- Open and control windows.
- Provide different documents or parts thereof based on user request. Ie. Framed vs not-framed.
Javascript language Structure
- We can embed JavaScript with <html> tags. JavaScript has a simple, relaxed structure. You can include a single line of JavaScript in an HTML document, and it will act as a JavaScript program in itself. A JavaScript program can be simple-even as small as a single statement-or much more complicated For example, this is a simple JavaScript program to print a message:
Notes:
- The JavaScript Appears Between the <SCRIPT> and </SCRIPT> Tags
- The <!-- and --> tells the html viewer that the text (ie. JavaScript) between them are just "comments", thus it does not display them.
- // indicates the rest of the line is an JavaScript comment
- ; denotes the end of a statement
- document denotes the default html window
- .write is the method to write text out to an object, such as a window
Comment
Ø Comments are used in programming to store notes about something like logic, reminder etc.
Ø Comments are also used for de-bugging (finding and solving errors in the program)
Ø Statements or commands inside or within scope of comments are not executed or interpreted by the browser.
Example:-
/* value3=value1/value2;
document.write(value3); */
document.write(value1*value2);
Programing
<html>
<head>
<script language=”javascript">
<head>
<script language=”javascript">
document.write("This is my first programming")
</script>
</head>
<body>
</body>
</html>
</head>
<body>
</body>
</html>
Interacting With the User
A. Prompt (prompt string, default reply)
- The prompt command requires two parameter strings.
- The first is the prompt to display, the second is the default answer. If you do not want a default answer, just use "".
- It returns what the user typed s a string of characters
Example:-
Prompt(“Enter a number”)
Prompt(“Enter a number”,”12”)
B. Alerts
- The alert dialog box displays the message given to it.
- Only an OK response is allowed to the user.
- The script and HTML document halts execution until the user chooses the OK button.
- The phrase "JavaScript Alert" is included in the dialog box to let the user know what caused the alert.
Example:-
alert("Just Learning JavaScript, Please Be Patient");
It then returns with a value of True of OK choosen, or False if Cancel choosen.
Example:-
<h1>PICTURE</h1>
<SCRIPT LANGUAGE="JavaScript">
var animated_images= confirm("Load animated images");
if (animated_images)
{
document.writeln('<IMG SRC="file:///Z:/picds/112.jpg">');
}
else
{
document.write("LOADING fAIL");
}
</SCRIPT>
The var statement is used to declare a variable, and outside of a function its use is optional. While a variable can be declared simply by assigning it a value, it is good practice to use var.
Example 1:-
var colour = prompt("Enter favourite colour:", "Red");
Example 2:-
y=x-5;
z=y+5;
z=y+5;
Programing
<script language=“javascript”>
var a,b;
a=5;
b=7;
document.write(a+b);
</script>
Data Types
Data type means type of data stored by the variables. We don’t have to declare data type while declaring variables. Javascript automatically change data type after assigning the value to a variable. There are different types like; integer, number, string, date, Boolean etc.
- Number: - It converts the number into integer or float data type.
Example: - var a=5;
- String : - It is a text and used within the double quotes (“ “).
Example:- var a=“Ram”;
- Boolean: - Boolean means True or False
Javascript converts true or false into 1 or 0 whenever they are used in numerical expressions.
Example: - var a=true;
4. Null: - The null value indicates that a variable is un-initialized. It is the assigning value to a variable as blank.
Type Casting
JavaScript provides 3 main function for type casting:
1) eval()
2) parseInt()
3) parseFloat()
A) eval() :-This function evaluates the numeric value of the string.
syntax:
eval(number-represent as string)
Example :-
var value1;
var string1=“156”;
value1=eval(string1);
document.write(value1);
value1=eval(“56”);
document.write(“<br>”,value1);
B) parseInt()
This function is used to convert to the string value to the numeric one . The alphabetical characters after number are ignored.
Syntax:
parseInt(string)
Example:-
v1=parseInt(“123”) 123
v2=parseInt(“1.23”) 1
v3=parseInt(“156AB”); 156
v4=parseInt(“2.5ktm”) 2
v5=parseInt(“ktm56”) NaN
C) parseFloat()
This function is used to convert to the string to the floating number. The alphabetical characters after number are ignored.
Syntax:
parseFloat()
Example:-
var1=parseFloat(“123”); 123
var2=parseFloat(“1.23”) 1.23
var3=parseFloat(“2.5ktm”); 2.5
var4=parseFloat(“AB56”); NaN
Using <pre>tag to demonstrate escape characters.
Example:-
<script language=“javascript”>
document.write(“<pre>”);
document.write(“This is my first line”);
document.write(“\n This line should appear in second line”);
document.write(“The tab consists of :\t space”);
document.write(“</pre>”);
</script>
OPERATOR IN JAVASCRIPT
- Arithmetic Operators :-
• + Plus
• - Minus
• * Multiply
• / Divide
• % Modulus (To get the remainder)
- Assignment Operators:-
• = Equal to
• += Plus and Equal to
• -= Minus and Equal to
• *= Multiply and Equal to
• /= Divide and Equal to
• %= Modulus and Equal to
o Comparison operators:-
1) > Greater than
2) < Less than
3) >= Greater and Equal to
4) <= Less and Equal to
- Equality Operator:-
1) = = Equal to
2)! = Not Equal to
- Logical Operator:-
1) And (&&)
2) Or(||)
3) Not (!)
Logical operators are used to join multiple conditional statements to get the resulting Boolean value.
(i) and (&&): - The logical operator is used to join the statement such that the result will be true if and only if all the statement joined by this operator are true.
(ii) || (or) :- The || logical operator is used to join the statements such that the result will be true if any of the statement joined by the operator is /are true.
(iii) ! (Not / Unary): - The ! logical operator is used in statement to negate or invert the Boolean value.
Increment / Decrement operator
------------------------------
(1)++: -Increase the value of variable by one.
(2)--: -Decrease the value of variable by one.
Selection Statements
Selection statements are used to implement the branching concept of programming. Branching means making some interrupt in normal flow of the program control.
1) If Conditon: -Selection statements are basically used to apply some condition to the normal statement such that if the condition is true the statement will be executed other wise will be ignored (As comment).
Syntax:-
If(condition)
{
//statement
}
(ii)If …else: -This selection statement is used to evaluate the condition that have two action are true case and result will be true and if the condition is false it returns false.
Syntax : -
if(condition)
{
statement
}
else
{
statement
}
(iii) if…else if ....else :- This selection statement is used to implement the multiple condition with their respective actions.
if(condition1)
{
Statement
}
else if(condition2)
{
Statement
}
else if(condition3)
{
Statement
}
else
{
Statement
}
Switch selection statement
--------------------------------
Switch can be used when single variable has to be evaluated for different values and different operations have to be performed for value.
Syntax: -
switch(variable_name)
{
case 1:
{
Statement;
} break;
case 2:
{
Statement;
} break;
case 3:
{
Statement;
} break;
default:
{
Statement;
}
}
Example:
<script language="javascript">
var a=eval(prompt("enter day"))
switch(a)
{
case 1:
{
document.write("sunday")
break;
}
case 2:
{
document.write("monday")
break;
}
case 3:
{
document.write("tuesday")
break;
}
default:
{
document.write("last")
}
}
</script>
Array: -
Array is static data structure, where values are store with same array name but different index number.
Syntax: -
arrayName=new Array(item1,item2,item3,…..itemn)
Types of Array
1. Single-Dimension Array
2. Multi-Dimension Array
Note: -The index number of first element of array is 0[Zero].
The index number of last element of array is n-1.
Where n=total number of element in the array.
To Get the Total Length of Array
arrayname.length
Multi-Dimension Array
----------------------------
Basically multi-dimension array can described as array containing array as an element in it. The multi-dim. Array contain more than one index number.
Looping
Looping is the process of repeating statements for certain number of time or until some condition is true to stop the loop.
1) For loop: - For loop is generally used when number of time and repetition is known.
Syntax: -
for (initialization; loop-condition; increment/ decrement)
{
Statement
}
2) While loop: -While loop is used generally when the number at looping is not known.
2) While loop: -While loop is used generally when the number at looping is not known.
3) Do-while loop: -The do-while statement will execute a block of code at least once, then will repeat the loop as long as a condition is true.
Function
Function is the small modules of a program that works like a separate program. Functions are basically used to group the related statement together to make the programming easier to program, debug and analyze.
Advantage of function
(1) Division of work can be practically implemented.
(2) Reduction of code length and ultimately the program size.
(3) To make the re-usability easier.
(4) Adds in debugging etc.
Major operation of Function
(i) Declaration: - This is not required in javascript. Declaration means specifying the memory location where functions are stored.
(ii) Definition: -This means describing the working mechanism of the function.
(iii) Calling/Invoking: - This means using the function.
Automatic Invoking of function
Function can be called automatically in javascript using setInterval() function.
Syntax :- objectName=setInterval(“function()”, timedelay-in miliseconds)
Object Methods
1) window.alert(): -This method is used to display the string and other values in a alert box, with just ok button.
Syntax:-window.alert(string);
2) window.prompt(): -This method is used to get string value from the user.
Syntax: -window.prompt (message,default_value)
3)window.confirm() :-This methods is used to get true/false information from user for certain processing.
Syntax:-
window.confirm (“message”);
3) window.open() :-This method is used to open new instance of browser user.
5) window.close () :- This method is used to close the opened windows or the window in which the javascript code is present.
Properties of Object: Window
• Status:- Refers to the text display in the status bar.
• Default status: - Refers to the default status bar text, that display even after the content is changed by changing status properties.
Object: location
• Protocol:-method of the URL (universal resource location)
• Hostname: - hostname of the server.
• Location href: - The entire URL.
EVENT Triggered when
n Blur An element, such as a radio button, because inactive
n Click An element is clicked once
n Change The value of an element changes
n Error There is an error when loading a document or image
n Focus An element because active
n Load A document or image loads
n MouseOut The mouse moves off an element
n MouseOver The mouse moves an element
n Reset A form resets
n Select A user selects a field in a form
n Submit A user submits a form
n Unload A document unloads
String is also an object in JavaScript but we can directly create this object by assigning string value to any variables “new “ keyword is not needed to declare string.
• E.g. var a=“Ram”
1) toUpperCase() :- It displays or gives all the characters of a string to uppercase.
E.g var a=“kathmandu”
• document.write(a.toUpperCase())
2) toLowerCase() :- it displays all the characters of a string to lowercase.
E.g. alert(a.toLowerCase())
3) length :- It displays or count the number of characters in the strings.
• e.g. alert(a.length)
4) substring() :- It is used to extract a string from another string.
e.g. var a=“kathmandu”
alert(a.substring(4,7))
here 4 is starting and 7 is ending position.
Object History:
History object is used to keep track of all the visited pages such that those visited page must be re-downloaded which save download time.
Methods
ð back(): - goes back to the previous location.
ð forward(): -goes forward to the next location.
Date Object (Method)
Ø getYear() = returns the currents Year as two digit.
Ø getDate() =returns the day of the months.(1-3)
Ø getMonth() = returns the month of the current date.(0- 11)
Ø getHours() = returns the hours of the current time.
Ø getMinutes() = returns the minutes of the current time.
Ø getSeconds() = returns the seconds of time.
Automatic Invoking of function
Function can be called automatically in javascript using setInterval() function.
Syntax :- objectName=setInterval(“function()”, timedelay-in miliseconds)
No comments:
Post a Comment