0% found this document useful (0 votes)
5 views

Java script

JavaScript is a scripting language used to create dynamic web pages that can update content at runtime. It provides various functions, properties, and objects to interact with HTML elements and is executed by popular web browsers. The document outlines how to use JavaScript, including internal, inline, and external scripts, as well as common objects, data types, operators, control statements, and event handling.

Uploaded by

123shreyashukla
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Java script

JavaScript is a scripting language used to create dynamic web pages that can update content at runtime. It provides various functions, properties, and objects to interact with HTML elements and is executed by popular web browsers. The document outlines how to use JavaScript, including internal, inline, and external scripts, as well as common objects, data types, operators, control statements, and event handling.

Uploaded by

123shreyashukla
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 39

- Java script :

- Java script is a scripting language that is used to create the dynamic web page

- Dynamic web page is the web page where we can update the contents

of page during run time

- It is used to implement the security, validation, cookies, controls etc.

- It provides various functions, properties, objects , structures, events to work

with html elements/contents at run time.

- It is a programming language that is executed by all of the popular web browsers

How to Use Java script:


1. Page Level / Internal java script

2. Inline Java script

3. External Java script

Steps :

Create the java script functions

Call / implement the function inside the web page over the html control

Note : There are various event handlers are used with Html Control to handle java

script function/code. most common handler is 'onClick' that handle the click

event.

Syntax for creating Java script code/ function :


1. Internal / page level :
...

<head>

<script type="text/javascript">

function Name_of_Function( Arguments )

.....

.....

..

..

</script>

</head>

<body>

............

call the java script function here

.....

</body>

calling of function :
like :

<input type="button" value="click Here" onClick="Function_Name();"/>

Common Rules :

Java script is a case sensitive language, use the lower case to write code or

follow the syntax.


All statements must be terminated by semi colon (;)

2. Inline Java script :


<Html_Elements ..... Event_Handler = " Java_Script_Code " .../>

like

<input type="button" value="click here" onClick="document.write('hello');"/>

3. External Java Script :


Create a separate file

Create all the functions you want

save the file with extension .js (like-->javascript.js)

go to your html file (where you want to use java script)

write the following code in <head> section

<script type="text/javascript" src="javascript.js" ..> </script>

Note : to print/write something on web page , java script provides the method :-

document.write("....");

Here 'document' is a pre-define object of javascript and 'write' is the method associated

to that object.

there may be multiple methods that can be associated with a particular object.

javascript provides various of objects and their associated methods which we learn in

upcomming classes.
we can also write any html control using document.write() method, remember that all the

tags are enclosed inside "" and all the quotation("") inside the tag are replaced by ' '.

Example :

java1.html

java2.html

java3.html

-------------------------------------------------------------------------------------------------------------

Java Script Elements :


-------------------------------------------------------------------------------------------------------------

Objects

Events

DOM(data object model)

Property set for Html and Css elements

Data Types

Variable

Operators

Control Statements

Array/String/Date/...

-------------------------------------------------------------------------------------------------------------

Java srcipt inbuilt Objects:-

------------------------------------------------------------------------------------------------------------

- java script provides varius objects related to the web page.

- each object provides some functions to perform specific action/task related to particular

category.
- objects makes the working easy and fast.

- java script provides following objects :

1. document

2. form

3. frame

4. history

5. location

6. navigator

7. window

Note : java script is a case sensitive language.

document : it is used to refer current web page's body. we can access the html elements

of the page like Links, Heading, Controls(textbox,listbox,radioButtons....),

Images etc.

some methods are :

write()

writeln()

getElementById()

getElementByName()

some properties :

bgColor : to set background color

fgColor : to set font/text color


linkColor

selection

title

vlinkColor

URL

ex: document.html

example

1. <script type="text/javascript">

2. function getcube(){

3. var number=document.getElementById("number").value;

4. alert(number*number*number);

5. }

6. </script>

7. <form>

8. Enter No:<input type="text" id="number" name="number"/><br/>

9. <input type="button" value="cube" onclick="getcube()"/>

10. </form>
----------------------------------------------------------------

Woking with HTML body elements :

------------------------------------------------------------------------------------------------------------

- we can access the html elements also at rum time

- to do so, we should use the 'id' or 'name' property with html elements

- In java script , we can access that element using the method -

getElementById("id") or getElementByName("name")

- we can set the values/attributes/properties of html elements.


Point to rememeber:

- to insert text inside paragraph, div, span ,.. we use 'innerHTML' property

- to insert text inside controls like textbox, we use 'value' property

- we can also set/change the css properties of elements using java script

- to store/hold values inside java script function, we use variables

like this :

var a,b,c; // variable declaration

a=20; // set value to variable

b="ram";

c=12.33;

java script provides the variant type variable (no type is specified)

once we set the value, they become typed.

value / data types may be :

integer

float

character

string // we can use String class also

date // we can use Date class also

boolean

ex:

document.html

document1.html

document2.html

ex2:-
<html>
<head>
<title>document 1 </title>
<script type="text/javascript">
function start() {
document.getElementById("m1").scrollAmount="3";
}

function stop(){
document.getElementById("m1").scrollAmount="0";
}

</script>
</head>

<body>
<center>
<fieldset style="width:300px; height:400px; border-width:5px; border-style:double;">
<legend> Latest Updates </legend>

<marquee height="250" direction="up" scrollamount="3" id="m1" onMouseOver="stop();" onMouseOut="start();">


<i> New Batches will start from 1st April <br/><br/>
Result will be declared on 15th March <br/><br/>
Exam Forms can be filled upto 20 March<br/><br/>
</marquee>
</fieldset>
<br/>

<span align="right">
<a href="#" onClick="stop();"> stop scroll</a> &nbsp;&nbsp;&nbsp;&nbsp;
<a href="#" onClick="start();"> start scroll</a>
</span>
</body>
</html>
-------------------------------------------------------------------------------------------------------------

Java script MessageBox :

------------------------------------------------------------------------------------------------------------

Java script provides 3 types of messageboxes :

- alert()

- prompt()

- confirm()

alert() :

It shows the message in a messagebox

syntax:

alert("message");

or

alert("message" + variable);

ex:

alert.html
prompt() :

It shows the inputbox where user can type the data.

It returns the string type value

We can store the value to a variable

ex:

var nm;

nm=prompt("Enter your Name")

ex 2:

var a,b,c;

a=prompt("Enter no1 ");

b=prompt("Enter no2 ");

a=parseInt(a);

b=parseInt(b);

c=a+b

alert("Sum is :"+ c);

ex: prompt.html

confirm() : - It shows the Confirmation box with two options : yes and no (ok / cancel)

- It returns boolean value either 'true' or 'false'

- It is used with if statement like this :

if(confirm("Do you want to Exit ?"))


window.close(); // this statement is used to close browser

Note : here 'window' is also a java script object.

ex: confirm.html

<html>
<head>
<title>document 1 </title>
<script type="text/javascript">
var a,b,c;
function getInput(){
a=prompt("Enter first no ");
b=prompt("Enter Second no ");
a=parseInt(a);
b=parseInt(b);
}

function getSum() {
c=a+b;
alert("Sum is "+ c);
}

function exit() {
if(confirm("Do you want to close Browser ?")){
window.close();
}

</script>
</head>

<body>
<center>
<fieldset style="width:300px; height:200px; border-width:5px; border-style:double;">
<legend> Simple Arithmetic </legend>
<tr>
<td> <input type="button" value="Input" onClick="getInput();"/> </td>
<td> <input type="button" value="Sum" onClick="getSum();"/> </td>
</tr>
<tr><td colspan="2"><center> <input type="button" value="Close Browser " onClick="exit();"/> </td>
</table>
</fieldset>
</body>
</html>

-------------------------------------------------------------------------------------------------------------

Event and EventHandlers :

-------------------------------------------------------------------------------------------------------------

- Events are the Actions applied on control by user to make intraction with web

page.

- Events may be occured using either Mouse or Keybard

MouseEvents are :

Click

DblClick

MouseMove

MouseOver

MouseOut

MouseDrag

MouseUp

MouseDown
....

....

KeyboardEvents :

KeyUp

KeyDown

KeyPressed

KeyTyped

.....

EventHandlers:

They are the attributes used with html control to handle specific type of event.

they start with 'on' and followed by Event Name like - onClick.

Java script Event Handlers are :

onClick : occurs when an element is clicked

onDblclick : occurs when an element is double clicked

onChange : occurs when data in a control (textbox) is changed

onBlur : occurs when an element loses the input focus(cursor goes outside
of textbox)

onFocus : occurs when an element gets the focus

onKeyDown : occurs when a key goes down

onKeyPress : occurs when a key is pressed and key code is available

onKeyUp : occurs when a key goes up.

onLoad : occurs when a page loaded

onMouseDown : occurs when the mouse button goes down

onMouseUp : occurs when the mouse button goes up

onMouseMove : occurs when the mouse moves

onMouseOver : occurs when the mouse moves over the element


onMouseOut : occurs when the mouse leaves the element

onSubmit : occurs when user click on submit button

onUnload : occurs when page is unloaded.

Creating File Upload Control :

<input type="file" id=".." />

- It is used to upload any Image or other files and submit to the server

Examples :

Event1.html

Event2.html

Event3.html

Event4.html

Event5.html

Writing HTML Comments :

<!--

comments

-->

Writing Java Script Comments :

1.Single line comments :

// comments

2. Multi Line comments :


/*

........

........

*/

ex:-

Event2.html

-----------------------------------------------------------------------------------------------------------

Setting Attributes of Html Elements Using Java Script :

-------------------------------------------------------------------------------------------------------------

1. use the function - setAttribute()

Element.setAttribute("attribute","value");

2. use the 'javascript properties set'

Element.js-property = value;

like :

var a = document.getElementById("txtno1");

a.value=100;

or

a.setAttribute("value",100);

Attribute1.html

//Attribute2.html

DOM.html

-------------------------------------------------------------------------------------------------------------

Setting Styles Using Javascript

------------------------------------------------------------------------------------------------------------

syntax:

ELEMENT.setAttribute("style","property set");
or

ELEMENT.style.JsCssPropertySet = value;

Note :

When we use javascript to set Css Property, all the css property is written as camel case

like :-

background-color : backgroundColor

text-decoration : textDecoration

font-style : fontStyle

text-transform : textTransform

list-style-type : listStyleType

like :

var dv = document.getElementById("div1");

dv.style.backgroundColor="red";

or

dv.setAttribute("style","background-color:red");

dv.style.textTransform="uppercase";

dv.style.fontStyle="italic";

OR

dv.setAttribute("style","text-transform:uppercase;font-style:italic");
Attribute3.html

Attribute4.html

-------------------------------------------------------------------------------------------------------------

java script Data Types and Variable

-------------------------------------------------------------------------------------------------------------

..

..

..

..

..

..

..

..

-----------------------------------------------------------------------------------------------------------

Operators :

------------------------------------------------------------------------------------------------------------

Arithemetical Operator

Relational Operator / Comparision Operator

Logical Operator

Assignment Operator

Compound Assigment/ Short Hand Operators

Increment and Decrement Operator


Bit-wise Operator

Conditional / Ternary Operator

-------------------------------------------------------------------------------------------------------------

ArithMetical Operators :

- Used for simple methmetical operations

ex:

% : modulas operator , used to find reminder

ex :Operators.html

-----------------------------------------------------------------------------------------------------------

Relational Operator :

- Used to Compare two values

ex:

< > <= >= == !=

-----------------------------------------------------------------------------------------------------------

Logical Operators :

-Used to combine multiple conditions

ex:

&& (Logial And)

|| (Logical Or)

! (Logical Not)

-------------------------------------------------------------------------------------------------------------

Assignment Operator : used to assign value to variable

ex: =
------------------------------------------------------------------------------------------------------------

Compound Assignment or Short hand Operator :

- do the arithmetical operations with variable and store the result back to same

variable.

ex:

+= -= /= *= %=

ex:

var a=10;

a+=5; -----(same as) ----------------> a= a+5; -----------------------> result : a=15

------------------------------------------------------------------------------------------------------------

Increment Operator : ++ (used to increase the value by 1)

var a=10;

a++; ------------------> result : a->11

Decrement Operator : -- (used to decrease value by 1)

var a=10;

a--; -------------------> result : a->9

-------------------------------------------------------------------------------------------------------------

Conditional Operator :

?:

Used to check condition and then do any of the two expression depending on condition

syntax:

variable = (condition) ? expression-1 : expression-2;

ex:

[operator2.html]

-------------------------------------------------------------------------------------------------------------

java script Control Statements :


------------------------------------------------------------------------------------------------------------

- Controls statements in js are used to control the flow of


program execution and

put the data validity.

- There are following types of control statements :

-------> Branching

| |

| |

| -------> if statement

| -------> switch statement

| --------> conditional operator

-------> Looping

| |

| |

| -------> do statement

| -------> while statement

| --------> for statement

---------> Jump Statements

-----> break
-----> continue

-----> goto

------> return

Branching :

- Used to crete one or more conditional block inside funtion

- Conditional block is only executed when the given condition is satisfied

statements:

a. simple if
b. if else
c. multiple if
d. nested if

switch statment

conditional operator

Simple if :

used to create a conditional block without any alternative.

syntax:

if (<condition>) {

.......

.......

[ex: absolute.html]

if else Statement :

- used to create a conditional block with one alternative block.


- when condition becomes true, if block is get executed other wise else block

is excuted.

syntax:

if (<condition>) {

....

....

else {

.....

.....

Note : if any block has only one statement,we can skip the use of {}.

[ex:- bigNo.html, Voting.html, EvenOdd.html]

Multiple if :

used to create multiple alternatives conditions.

only one block get executed at a time that condition becomes true first.

if no codition is true, else block is executed.

if (<condition>) {

....

else if(<condition>){

....
}

else if(<condition>) {

.....

else {

.....

ex: input percentage in a textbox and show the division.

[Division.html]

Nested If :

- condition within condtion

- inner condition is only evaluated when outer condition is true

if (<condition>) {

if(<condtion>) {

...

else {

.....

ex : input any number in textbox and show the square if and only if the number is positive
as well as even.

[nestedIf1.html]

input the age of person and select the gender (from radio button). show the eligibility for

marrige inside the <span> in page.

[nestedif2.html]

Note : you can also use the logical operator - && in case of nesting.

ex: find big number amongest 3 numbers

[nestedIf3.html] and [logicalIf.html]

Switch Statement :

- Used to define the set of values to perform the particular type of action

- We can define the different actions over different values or same action over

different values.

- The source variable is written inside switch() and the values for comparision

are written along with 'case'.

Syntax:

switch(<variable>) {

case <value1> :

.......

break;

case <value2> :

...........

break;

case <value3> :

.............
break;

..

..

default :

.....

ex : Select the week day sequence from combobox (1 - 7) and show the name of the

realated day.

[dayExample.html]

Input two numbers in a text box and select the operations from combobox(Add,Sub.,Multi.,Div.) and do
the related operation.

[ChoiceOp.html]

Conditional Operator :

?:

Used to check condition and then do any of the two expression depending on condition

syntax:

variable = (condition) ? expression-1 : expression-2;

ex:

[operator2.html]

------------------------------------------------------------------------------------------------------------

Looping Statements :

- Used to repeate any block of statements

- Any Loop needs following elements to work :


Counter Initialization

Test Condition

Counter Updation

Statment Block

Note : counter is an Integer type variable like -

var i;

initialization ----> set the starting value of counter , like:-

i=1;

updation ---------> increase or decrease the value after each repeate , like

i++ i--

or

i=i+1 i=i-1

or

i+=1 i-=1

condition ------------> to specify how long the looping goes on , like-

while(i<=10)

statement block -------> the statement(s) which are executed during the looping, like

...

document.write(i); //print value of i

-----------------------------------------------------------------------------------------------------------

do statement : It excuted the statement first then check the condition, so it is an exit control loop

syntax:

<set counter>

do {

........
......... <statements>

......... <updation>

} while(<condition>);

ex: show the numbers from 1 to 10 when user run/open the browser.

function show() {

var i=1; // set counter

do {

document.write("<br/>"+i); //statment that print 1 to 10

i++; // increase 'i' by 1 for next value

} while(i<=10); //condition for looping

while Statement :

- It is entry control loop statement

- Condition is specified before the code body

- Each time it check condition first then repeate the loop until the condition

become false

Syntax:

<set counter>

while (<condition>) {

.....
..... //statements

......//updation

ex:

show the number 20 to 1

function show() {

var i=20;

while (i>=1) {

document.write("<br/>"+i);

i--;

...

...

<body onLoad="show();">

...

</body>

Q. Input a number to textbox and show the table of number when user click on button.

...

function table() {

var n,i,t;

n=document.getElementById("txt1").value;

i=1;
while(i<=10) {

t=n*i;

document.write("<br/>" + n + "*" + i + "=" + t);

i++;

...

...

<body>

.......

...... <input type="text" id="txt1"/>

<input type="button" value="show Table" onClick="table();"/>

</body>

for loop :

- It is single line loop statement

- we set the counter,condition and updation in a single line

Syntax:

for(<set counter>; <condition> ; <updation>) {

..... //only statements

ex: show number 1 to 10

....
function showNum() {

var i;

for(i=1;i<=10;i++)

document.write("<br/>"+i);

.....

<body onLoad="showNum();">

...

</body>

see :

loop1.html

loop2.html

loop3.html

loop4.html

loop5.html

-------------------------------------------------------------------------------------------------------------

jump statements :

used to shift the control of program from one place to another place.

they are :-

1. break : It is used to terminate the current loop body and jump out side of block.

loop does not repeate back after break.

ex:

for (i=1;i<=100;i++) {
if (i>=10)

break;

document.write("<br/>"+i);

output :

..

2. continue :

- It used to return the loop back from specific position.

- It does not terminate loop , but it skip the further statements.

for(i=1;i<=100;i++ {

if (i>10 && i<90)

continue;

document.write("<br/>"+i);

output:

..

10

90

91

...
100

goto :

- used to transfer control either backward or forward inside the function

- we have to specify the label with goto statement

- label can be created any where inside the function followed by color (:)

ex:

function show() {

var i=1;

print :

document.write("<br/>" + i);

i++;

if(i<10) { goto print; }

output :

-------------------------------------------------------------------------------------------------------------

String , Date and Array

-------------------------------------------------------------------------------------------------------------

String :
- It is a set of characters

- Javascript provides the 'String' Class to work with string

- we can create object of String class then use the various String methods also.

creating Object :

<obj> = new String();

or

<obj> = new String("<text>");

like

name = new String();

or

name = new String("ramesh");

addr = new String();

addr = "D-17, Nehru Nagar, Bhopal";

String Functions : -

toUpperCase()

toLowerCase()

substring()

length()

contains()

startsWith()

endsWith()
indexOf()

charAt()

equals()

toUpperCase() and toLowerCase() : retuns the uppercase and lower case of the string

like:

function show() {

nm = new String();

nm= document.getElementById("txtnm").value;

alert("Name in Upper Case : " + nm.toUpperCase());

..

substring() : -> It returns a section or part of string.

we specify the starting index and number of characters

substr(<starting index> , <num of chars>);

like :

nm = new String("Ramesh");

var nm2 = nm.substring(2,2);

alert(nm2); // output : me

var nm3 = nm.substring(0,3);

alert(nm3); // output : Ram


length() : - It returns the number of characters in string including spaces.

ex:

Nm = new String("Ram Ji");

// or Nm = document.getElementById("txtnm").value;

var n= Nm.length();

alert("Total number of characters :"+ n);// output : 6

indexOf() : It returns the postion of any character inside the string.

It returns the fist time postion of the character or word

If character not found, it returns -1

like :

str = new String("welcome to India");

var n = str.indexOf("e");

alert("first position of e : "+ n); //output :1

charAt() : It is used to get the character of any position.

like :

Nm = new String("Amriesh");

var ch = Nm.charAt(3);

alert(ch); //output --> i


startsWith() and endsWith() : used to check the starting and ending characters.
usually used with if statement.

ex:

Nm=new String("Mrs. Priya Agrawal");

if (Nm.startsWith("Mr.")

document.write("Welcome Sir");

else if(Nm.startsWith("Mrs")

document.write("Welcome Madam");

else

document.write("Welcome");

equas() : used to compare two string

we can also use '= =' operator

like

nm1=new String("ramesh");

nm2=new String("Ramesh");

if(nm1.equals(nm2)) // if(nm1==nm2)

alert("Both names are same");

else

alert("Both names are different");

output : Both names are different

__________________________________________________________________
Array :

- It is a set of multiple values/data of same type

- we can store more than one values inside single array

syntax :

<variable> = new Array(<Size>);

like :

a = new Array(5);

// we can store 5 values inside 'a'

how to store value :

use the scripting operator [] for each index

index begins from 0

like :

A = new Array(5);

A[0]=10;

A[1]=100;

A[2]=30;

A[3]=50;

A[4]=200;

we can also use loop to access the values of array like this :

// show all the values from array 'A'


for(i=0;i<=4;i++)

document.write("<br/>" + A[i]); // here value of i goes from 0 to 4

example :

Enter 5 names in an array and show all the names in web page.

[array.html]

------------------------------------------------------------------------------------------------------------

creating function:
part of function==>
1. function declaration
2. function definition
3. function calling

= Function is a set of statement that perform any specific task or operation

= Any Function needs to be invoked(called) inside the body section where

we want to perform particular operation

= Function makes the code/statements reusable. means we define the function once but we
can call them many time.

syntax:

function <name>(...)

....

like :

function show() {

....
}

types of functions:

1. Non-Parametrized : That does not accept any argument

2. Parametrized : That accept the argument and user can pass the value
at the time of function call.

like :

function sum(x,y)

var z= x+y;

document.write("sum is "+z);

..

<body onLoad="sum(2,40);">

</body>

3. Returning Values from Function :

function <name> ( ..) {

...

return(<value/expression>);

example:
<script....>

function sum(x,y,z) {

return(x+y+z);

function average(x,y,z) {

var av = sum(x,y,z)/3.0; //nesting of function

document.write("average : "+av);

..

<body onLoad="average(20,40,80);">

</body>

-------------------------------------------------------------------------------------------------------------

You might also like