[go: up one dir, main page]

0% found this document useful (0 votes)
8 views41 pages

12 Chapter 3 Javascript Imp Points

This document provides important notes on JavaScript, covering topics such as scripting, looping structures (for and while loops), and various JavaScript objects (Window, String, Math, Date, Array). It includes examples of code execution, explanations of syntax, and step-by-step breakdowns of programs. Additionally, it outlines the Document Object Model (DOM) and event handling in JavaScript.

Uploaded by

g17181210
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views41 pages

12 Chapter 3 Javascript Imp Points

This document provides important notes on JavaScript, covering topics such as scripting, looping structures (for and while loops), and various JavaScript objects (Window, String, Math, Date, Array). It includes examples of code execution, explanations of syntax, and step-by-step breakdowns of programs. Additionally, it outlines the Document Object Model (DOM) and event handling in JavaScript.

Uploaded by

g17181210
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

12 STD SCI CHAPTER 3

JAVASCRIPT IMP NOTES


(TEXTBOOK PAGE NO 35 PDF PAGE NO 45)
Contents
SCRIPTING ............................................................................................. 3
Switch case and Looping Structures ......................................................... 3
1. for…….loop ....................................................................................... 3
Example of for loop : ............................................................................. 3
2. While…..loop ..................................................................................... 4
Example of while loop : ......................................................................... 4
Program for table of any number entered by user ..................................... 4
Output for 1 program of table of any number........................................ 5
Break and continue statements ................................................................. 5
Program for Prime Number ...................................................................... 5
3.3 Objects in JavaScript .......................................................................... 6
DOM (Document Object Model) : (5points) ............................................ 7
W3C (World Wide Web Consortium) .................................................... 7
DOM 4 properties and 3 methods ............................................................. 8
Dom Properties : 1) Head 2)title 3)URL 4)body,img ............................. 8
Dom Methods : 1)write() 2)writeln 3) getElementById() ...................... 8
The innerHTML Property ......................................................................... 8
Objects in Javascript are 1) Window 2)String 3)Math 4)Date 5)Number
6)Array ..................................................................................................... 9
Window Object: 4 points .......................................................................... 9
Windows Objects 4 properties and 9 Methods ......................................... 9
Window Property : 1)Name 2)Location 3)Document 4)closed .............. 9
Window Method : 1)alert() 2)confirm() 3)prompt() 4)open() 5)close()
6)blur() 7)focus() 8)print() 9)setTimeout()............................................. 9
3.4 JavaScript Event ............................................................................... 10
Event Handler of Javascript (8 Events) .................................................. 10
8 events : 1)onblur 2)onfocus 3)onchange 4)onselect 5)onsubmit 6)onreset
7)onload 8)onunload ............................................................................ 10
String Object:1 Property 8 Methods ....................................................... 11
String Object Property : Length ........................................................... 11
String Object Method : 1)charAt() 2) indexOf() 3)lastIndexOf() 4)
lastIndexOf() 5) substr() 6) substring() 7) toLowerCase() 8) toUpperCase()
............................................................................................................. 11
Math Object : 9 Methods ........................................................................ 13
Math Object Method: 1)abs(x) 2)cbrt(x) 3)ceil(x) 4)floor(x) 5)max(x,y)
5)min(x,y) 6)pow(x,y) 7)random(x) 8)sqrt(x) ...................................... 13
Date Object : 16 Methods ....................................................................... 14
Date Method : 1) getDate()2)getDay()3)getFullYear() 4)getHours()
5)getMinutes() 6)getMonth() 7)getSeconds() 8)getTime() 9)now()
10)setDate() 11)setFullYear() 12)setHours() 13)setMinutes() 14)setMonth()
15)setSeconds() 16)setTime() .............................................................. 14
Number Object : 3 Property 4 Method ................................................... 17
Number Object Property : 1)MIN_VALUE 2)MAX_VALUE 3) NaN 17
Number Methods :1)isInteger() 2)parseFloat() 3)parseInt() 4)isFixed()17
Array Object 5 points ............................................................................. 17
Array Object : 2 Property 10 Methods .................................................... 18
Array Object Property: 1) index 2) length ............................................ 18
Array Object Method: 1)concat 2)copywithin 3)find() 4)forEach()
5)indexOf() 6)isArray() 7)pop() 8)push() 9)reverse() 10)sort() ........... 18
Summary ................................................................................................ 18
Journal Program...................................................................................... 19
Practical 8 from Journal .......................................................................... 19
Ans 8 Coding --> Filename: Color.html............................................... 19
Coding --> Filename: Color1.html ...................................................... 21
Practical 9 Question ................................................................................ 22
Practical 9 Ans ........................................................................................ 22
Practical 9 Output ................................................................................. 23
Practical 10 Question .............................................................................. 23
Practical 10 : Ans :.................................................................................. 23
Practical 10 Output ............................................................................... 25
FILL IN THE BLANKS ......................................................................... 25
TRUE OR FALSE .................................................................................. 26
MCQ ONE CORRECT ANSWER...................................................... 26
MCQ TWO CORRECT ANSWER .................................................... 27
MATCH THE FOLLOWING ................................................................ 28
MARKS DISTRIBUTION ................................................................... 28

SCRIPTING
There are two types of scripting :
Client-side Scripting:
Server-side Scripting:

Switch case and Looping Structures


3.2.1 Switch Case statement
3.2.2 Looping Statement

1. for…….loop
This loop executes statements as long as condition becomes true, control
comes out from the loop when condition becomes false.
Benefit of for-loop is that it combines initialization, condition and loop
iteration (increment or decrement) in single statement.

Syntax :
for(initialization;condition;iteration)
{
statement block;
}

Example of for loop :


for(i=1;i<=5;i++)
{
document.writeln(i);
}

Textbook Program 1
JavaScript code step by step:
1. for (i = 1; i <= 5; i++):
- `for` is a keyword that starts the loop.
- `(i = 1;` initializes the loop, setting the variable `i` to 1. This is the
starting point of the loop.
- `i <= 5;` is the condition that keeps the loop running. The loop will
continue as long as `i` is less than or equal to 5.
- `i++` increments the value of `i` by 1 after each iteration. This means that
`i` will increase by 1 every time the loop runs.
2. `{`:
- This curly brace `{` marks the beginning of the code block that will be
executed in each iteration of the loop.

3. document.writeln(i);
- `document` is an object that represents the web page.
- `writeln` is a method that writes a line of text to the web page.
- `(i)` is the variable that currently holds the value of `i`.
In each iteration, this value will be written to the web page.
4. `}`:
- This curly brace `}` marks the end of the code block for the loop.

Step-by-Step Execution:
1. The loop starts with `i` set to 1.
2. It checks the condition `i <= 5`. Since 1 is less than or equal to 5, the
condition is true.
3. It executes `document.writeln(i);`, which writes the number 1 to the web
page.
4. After writing the number, `i` is incremented by 1 (so `i` becomes 2).
5. The loop checks the condition `i <= 5` again. Since 2 is less than or equal
to 5, the condition is true.
6. It writes the number 2 to the web page.
7. This process repeats until `i` reaches 6.
8. When `i` is 6, the condition `i <= 5` becomes false, and the loop stops.

So, the output of this code will be the numbers 1, 2, 3, 4, and 5 written in
sequence on the web page.

Textbook Program2
<script>
for (let i = 0; i < 5; i++)
{
document.writeln(i+"<br>");
}
</script>

JavaScript code step by step program 2:

javascript
<script>
for (let i = 0; i < 5; i++)
{
document.writeln(i + "<br>");
}
</script>
1. <script>:
- This tag tells the browser that the following content is JavaScript code.

2. for (let i = 0; i < 5; i++):


- `for` is a keyword that starts the loop.
- `(let i = 0;` initializes the loop, setting the variable `i` to 0. This is the
starting point of the loop.
- `i < 5;` is the condition that keeps the loop running. The loop will
continue as long as `i` is less than 5.
- `i++` increments the value of `i` by 1 after each iteration. This means that
`i` will increase by 1 every time the loop runs.

3. `{`:
- This curly brace `{` marks the beginning of the code block that will be
executed in each iteration of the loop.

4. **`document.writeln(i + "<br>");`**:
- `document` is an object that represents the web page.
- `writeln` is a method that writes a line of text to the web page.
- `i` is the variable that currently holds the value of `i`. In each iteration,
this value will be written to the web page.
- `+ "<br>"` adds a line break after each number. The `<br>` tag in HTML
creates a line break, so each number will be on a new line.
5. `}`:
- This curly brace `}` marks the end of the code block for the loop.
6. `</script>`**:
- This tag closes the JavaScript code section.

Step-by-Step Execution:
1. The loop starts with `i` set to 0.
2. It checks the condition `i < 5`. Since 0 is less than 5, the condition is true.
3. It executes `document.writeln(i + "<br>");`, which writes the number 0
followed by a line break to the web page.
4. After writing, `i` is incremented by 1 (so `i` becomes 1).
5. The loop checks the condition `i < 5` again. Since 1 is less than 5, the
condition is true.
6. It writes the number 1 followed by a line break to the web page.
7. This process repeats until `i` reaches 5.
8. When `i` is 5, the condition `i < 5` becomes false, and the loop stops.

So, the output of this code will be the numbers 0, 1, 2, 3, and 4, each on a
new line on the web page.
Explanation
for (let i = 0; i < 5; i++) {: This sets up a loop that will run 5 times, with i
taking values from 0 to 4.

document.writeln(i + "<br>");: This writes the value of i to the document


followed by a <br> tag, which inserts a line break after each number.
Output:
1
2
3
4
5

Textbook Program 3

for(i=5;i>=1;i--)
{
document.writeln(i);
}

Output:
5
4
3
2
1
Sure, let's break down this JavaScript code step by step:

```javascript
for (i = 5; i >= 1; i--) {
document.writeln(i);
}
```

1. **`for (i = 5; i >= 1; i--)`**:


- `for` is a keyword that starts the loop.
- `(i = 5;` initializes the loop, setting the variable `i` to 5. This is the
starting point of the loop.
- `i >= 1;` is the condition that keeps the loop running. The loop will
continue as long as `i` is greater than or equal to 1.
- `i--` decrements the value of `i` by 1 after each iteration. This means that
`i` will decrease by 1 every time the loop runs.

2. **`{`**:
- This curly brace `{` marks the beginning of the code block that will be
executed in each iteration of the loop.

3. **`document.writeln(i);`**:
- `document` is an object that represents the web page.
- `writeln` is a method that writes a line of text to the web page.
- `i` is the variable that currently holds the value of `i`. In each iteration,
this value will be written to the web page.

4. `}`:
- This curly brace `}` marks the end of the code block for the loop.

Step-by-Step Execution:
1. The loop starts with `i` set to 5.
2. It checks the condition `i >= 1`. Since 5 is greater than or equal to 1, the
condition is true.
3. It executes `document.writeln(i);`, which writes the number 5 to the web
page.
4. After writing the number, `i` is decremented by 1 (so `i` becomes 4).
5. The loop checks the condition `i >= 1` again. Since 4 is greater than or
equal to 1, the condition is true.
6. It writes the number 4 to the web page.
7. This process repeats until `i` reaches 0.
8. When `i` is 0, the condition `i >= 1` becomes false, and the loop stops.

So, the output of this code will be the numbers 5, 4, 3, 2, and 1 written in
sequence on the web page.

2. While…..loop
This loop executes statements as long as the condition is true. As soon as
condition becomes false control comes out of the loop.
Syntax:
initialization;
while(condition)
{
statement block;
iteration
}

Example of while loop :


var i=1
while(i<=5)
{
document.writeln(i);
i=i+1;
}

Explanation of the program step by step


1. `var i = 1;`:
- `var` is a keyword used to declare a variable.
- `i` is the name of the variable.
- `= 1` sets the initial value of `i` to 1.

2. `while (i <= 5)`


- `while` is a keyword that starts a loop.
- `(i <= 5)` is the condition for the loop. The loop will continue to run as
long as `i` is less than or equal to 5.

3. `{`:
- This curly brace `{` marks the beginning of the code block that will be
executed in each iteration of the loop.

4. `document.writeln(i);`:
- `document` is an object that represents the web page.
- `writeln` is a method that writes a line of text to the web page.
- `i` is the variable that currently holds the value of `i`. In each iteration,
this value will be written to the web page.

5. `i = i + 1;`:
- This line increments the value of `i` by 1. It means that the current value
of `i` is added to 1, and the result is stored back in `i`.

6. `}`:
- This curly brace `}` marks the end of the code block for the loop.

Step-by-Step Execution:

1. The loop starts with `i` set to 1.


2. It checks the condition `i <= 5`. Since 1 is less than or equal to 5, the
condition is true.
3. It executes `document.writeln(i);`, which writes the number 1 to the web
page.
4. It then executes `i = i + 1;`, which increments `i` by 1 (so `i` becomes 2).
5. The loop checks the condition `i <= 5` again. Since 2 is less than or equal
to 5, the condition is true.
6. It writes the number 2 to the web page and increments `i` by 1 (so `i`
becomes 3).
7. This process repeats until `i` reaches 6.
8. When `i` is 6, the condition `i <= 5` becomes false, and the loop stops.

So, the output of this code will be the numbers 1, 2, 3, 4, and 5 written in
sequence on the web page.

Feel free to ask if you need any further clarification or have more questions!

Program for table of any number entered by user


<!DOCTYPE html>
<head><title>Table-I</title>
<script type="text/javascript">
function display()
{
var i,a;
a=form1.t1.value
for(i=1;i<=10;i++)
{
document.write(a*i + "<br/>");
}
}
</script></head>
<body>
<form name="form1">
Enter number to display table:-
<input type="text" name="t1">
<input type="button" value=" Display Table" onClick="display()">
</body>
</html>

Output for 1 program of table of any number


Sure, let's break down the HTML and JavaScript code step by step:

```html
<!DOCTYPE html>
<html>
<head>
<title>Table-I</title>
<script type="text/javascript">
function display() {
var i, a;
a = form1.t1.value;
for (i = 1; i <= 10; i++) {
document.write(a * i + "<br/>");
}
}
</script>
</head>
<body>
<form name="form1">
Enter number to display table:-
<input type="text" name="t1">
<input type="button" value="Display Table" onClick="display()">
</form>
</body>
</html>
```

Line by Line code explaination


1. `<!DOCTYPE html>` :
- This declaration defines the document type and version of HTML. It
ensures that the document is interpreted as HTML5.

2. **`<html>`**:
- This tag starts the HTML document.

3. **`<head>`**:
- This section contains meta-information about the document, such as its
title and linked resources like CSS and JavaScript.

4. **`<title>Table-I</title>`**:
- This sets the title of the web page, which appears in the browser tab.

5. **`<script type="text/javascript">`**:
- This tag indicates that the enclosed content is JavaScript code.
6. **`function display()`**:
- This defines a function named `display`. A function is a block of code
designed to perform a specific task when called.

7. **`{`**:
- This curly brace `{` marks the beginning of the function's code block.

8. **`var i, a;`**:
- `var` is a keyword used to declare variables.
- `i` and `a` are variable names.

9. **`a = form1.t1.value;`**:
- This assigns the value entered in the text input (named `t1` in the form
`form1`) to the variable `a`.

10. **`for (i = 1; i <= 10; i++)`**:


- `for` is a keyword that starts a loop.
- `(i = 1;` initializes the loop, setting the variable `i` to 1.
- `i <= 10;` is the condition that keeps the loop running as long as `i` is less
than or equal to 10.
- `i++` increments the value of `i` by 1 after each iteration.

11. **`{`**:
- This curly brace `{` marks the beginning of the loop's code block.

12. **`document.write(a * i + "<br/>");`**:


- `document` is an object representing the web page.
- `write` is a method that writes content to the web page.
- `a * i` calculates the product of `a` and `i`.
- `+ "<br/>"` appends an HTML line break to ensure each result appears
on a new line.

13. **`}`**:
- This curly brace `}` marks the end of the loop's code block.

14. **`}`**:
- This curly brace `}` marks the end of the function's code block.

15. **`</script>`**:
- This tag closes the JavaScript code section.

16. **`<body>`**:
- This section contains the content of the web page that is visible to users.

17. **`<form name="form1">`**:


- This defines a form element named `form1`.

18. **`Enter number to display table:-`**:


- This is a text label prompting the user to enter a number.

19. **`<input type="text" name="t1">`**:


- This creates a text input field for the user to enter a number. The input is
named `t1`.

20. **`<input type="button" value="Display Table"


onClick="display()">`**:
- This creates a button labeled "Display Table".
- `onClick="display()"` is an event handler that calls the `display` function
when the button is clicked.

21. **`</form>`**:
- This tag closes the form element.

22. **`</body>`**:
- This tag closes the body section of the HTML document.

23. `</html>`:
- This tag closes the HTML document.

Step-by-Step Execution:
1. When the user enters a number into the text input field and clicks the
"Display Table" button, the `display` function is called.
2. The function retrieves the entered number from the input field and assigns
it to the variable `a`.
3. The function then loops from 1 to 10, multiplying the entered number `a`
by the current loop index `i`.
4. For each iteration, the result of `a * i` is written to the web page, followed
by a line break (`<br/>`).
5. This process generates a multiplication table for the entered number,
displaying each result on a new line.

Break and continue statements


Break statement is used to jump out of loop.
Break statement is used to make an early exit from a loop.
When keyword break is encountered inside the loop, control automatically
passes to the next statemen after the loop.
Sometimes in looping it may be necessary to skip statement block and take
the control at the beginning for next iteration. This is done by using
‘continue’ statement in JavaScript.
Program for Prime Number
<!DOCTYPE html>
<html><head><title>Prime number</title>
<script type="text/javascript">
function display()
{
var a,ans;
a=parseInt(form1.t1.value);
ans=1;
for(i=2;i<a;i++)
{
if(a%i==0)
{
ans=0;
break;
}
}
if(ans==1)
alert("Number is prime");
else
alert("Number is not prime");
}
</script></head>
<body>
<h1 align="center"> Program to check number is prime or not </h1>
<form name="form1" style="text-align:center">
Enter your Number (Greater than one):-<input type="text" name="t1"> <br>
<input type="button" value="check Prime number" onClick="display()">
</body>
</html>
Let's break down this HTML and JavaScript code step by step:

```html
<!DOCTYPE html>
<html>
<head>
<title>Prime number</title>
<script type="text/javascript">
function display() {
var a, ans;
a = parseInt(form1.t1.value);
ans = 1;
for (i = 2; i < a; i++) {
if (a % i == 0) {
ans = 0;
break;
}
}
if (ans == 1)
alert("Number is prime");
else
alert("Number is not prime");
}
</script>
</head>
<body>
<h1 align="center">Program to check number is prime or not</h1>
<form name="form1" style="text-align:center">
Enter your Number (Greater than one):-<input type="text" name="t1">
<br>
<input type="button" value="check Prime number" onClick="display()">
</form>
</body>
</html>
```

Line by line code explanation


1. `<!DOCTYPE html>`
- This declaration defines the document type and version of HTML. It
ensures that the document is interpreted as HTML5.

2. `<html>`:
- This tag starts the HTML document.

3. `<head>`:
- This section contains meta-information about the document, such as its
title and linked resources like CSS and JavaScript.

4. **`<title>Prime number</title>`**:
- This sets the title of the web page, which appears in the browser tab.
5. **`<script type="text/javascript">`**:
- This tag indicates that the enclosed content is JavaScript code.

6. **`function display()`**:
- This defines a function named `display`. A function is a block of code
designed to perform a specific task when called.

7. **`{`**:
- This curly brace `{` marks the beginning of the function's code block.

8. **`var a, ans;`**:
- `var` is a keyword used to declare variables.
- `a` and `ans` are variable names.

9. **`a = parseInt(form1.t1.value);`**:
- This line retrieves the value entered in the text input (named `t1` in the
form `form1`) and converts it to an integer using `parseInt()`. The result is
stored in the variable `a`.

10. **`ans = 1;`**:


- This line initializes the variable `ans` to 1. It will be used to determine if the
number is prime.

11. **`for (i = 2; i < a; i++)`**:


- `for` is a keyword that starts a loop.
- `(i = 2;` initializes the loop, setting the variable `i` to 2. This is the starting
point of the loop.
- `i < a;` is the condition that keeps the loop running as long as `i` is less
than `a`.
- `i++` increments the value of `i` by 1 after each iteration.

12. **`{`**:
- This curly brace `{` marks the beginning of the loop's code block.

13. **`if (a % i == 0)`**:


- `if` is a keyword that starts a conditional statement.
- `(a % i == 0)` checks if `a` is divisible by `i` without a remainder (i.e., `a`
modulo `i` is 0). If true, it means `a` is not a prime number.

14. **`{`**:
- This curly brace `{` marks the beginning of the `if` statement's code block.

15. **`ans = 0;`**:


- This line sets `ans` to 0, indicating that `a` is not a prime number.

16. **`break;`**:
- This statement exits the loop immediately, as there's no need to check
further.

17. **`}`**:
- This curly brace `}` marks the end of the `if` statement's code block.
18. **`}`**:
- This curly brace `}` marks the end of the loop's code block.

19. **`if (ans == 1)`**:


- This `if` statement checks if `ans` is still 1, indicating that `a` is a prime
number.

20. **`alert("Number is prime");`**:


- If `ans` is 1, this line displays an alert message stating "Number is prime".

21. **`else`**:
- This keyword specifies an alternative block of code to execute if the `if`
condition is not met.

22. **`alert("Number is not prime");`**:


- If `ans` is 0, this line displays an alert message stating "Number is not
prime".

23. **`}`**:
- This curly brace `}` marks the end of the function's code block.

24. **`</script>`**:
- This tag closes the JavaScript code section.

25. **`<body>`**:
- This section contains the content of the web page that is visible to users.

26. **`<h1 align="center">Program to check number is prime or not</h1>`**:


- This creates a header with the text "Program to check number is prime or
not" and aligns it to the center of the page.

27. **`<form name="form1" style="text-align:center">`**:


- This defines a form element named `form1` and aligns its content to the
center.

28. **`Enter your Number (Greater than one):-`**:


- This is a text label prompting the user to enter a number.

29. **`<input type="text" name="t1">`**:


- This creates a text input field for the user to enter a number. The input is
named `t1`.

30. **`<br>`**:
- This HTML tag inserts a line break to separate the input field from the
button.

31. **`<input type="button" value="check Prime number"


onClick="display()">`**:
- This creates a button labeled "check Prime number".
- `onClick="display()"` is an event handler that calls the `display` function
when the button is clicked.

32. **`</form>`**:
- This tag closes the form element.

33. **`</body>`**:
- This tag closes the body section of the HTML document.

34. **`</html>`**:
- This tag closes the HTML document.

Step-by-Step Execution:
1. When the user enters a number into the text input field and clicks the "check
Prime number" button, the `display` function is called.
2. The function retrieves the entered number, converts it to an integer, and
stores it in the variable `a`.
3. The function initializes the variable `ans` to 1, assuming the number is
prime.
4. The loop starts with `i` set to 2 and continues as long as `i` is less than `a`.
5. For each iteration, the function checks if `a` is divisible by `i`. If it is, `ans` is
set to 0, indicating the number is not prime, and the loop breaks.
6. After the loop, the function checks the value of `ans`. If `ans` is still 1, an
alert message stating "Number is prime" is displayed. Otherwise, an alert
message stating "Number is not prime" is displayed.

This code effectively checks if the entered number is a prime number and
displays an appropriate message.

3.3 Objects in JavaScript


JavaScript is an object-based scripting language.
Almost everything is an object in JavaScript.
A JavaScript object is an entity having state (properties) and behavior
(methods).
Objects such as table, board, television, bicycle, shop, bus, car, monitor etc.
All these tangible things are known as objects.
Object Car has properties like name, model, weight, color etc. and methods
like start, stop, brake etc.

Properties and methods of object's are accessed with '.' operator.


JavaScript supports 2 types of objects
Built-in objects and User defined objects.
1. Built in objects such as Math, String, Array, Date etc.
2. JavaScript gives facility to create user defined objects as per user
requirements.
The ‘new’ keyword is used to create new object in JavaScript.
e.g.
d= new Date();
// ‘d’ is new instance created for Date object.

DOM (Document Object Model) : (5points)


1. When HTML document is loaded into a web browser, it becomes a
document object.
2. DOM defines logical structure of document.
3. The way in which HTML document content is accessed and modified is
called as Document Object Model.
4. DOM is programming interface for HTML and XML (Extensible
Markup Language) documents.
5. The standardization of DOM was founded by W3C (World Wide Web
Consortium)
W3C (World Wide Web Consortium)
W3C works for standardization of web technologies.
According to W3C :
"The W3C Document Object Model (DOM) is a platform and language
neutral interface that allows programs and scripts to dynamically access and
update the content, structure, and style of a document."

DOM 4 properties and 3 methods


Following are some of the predefined methods and properties for DOM
object.
Dom Properties : 1) Head 2)title 3)URL 4)body,img
Dom Methods : 1)write() 2)writeln 3) getElementById()
SrNo Properties Description
Returns the <head> element of
1 Head
thedocument
Sets or returns title of the
2 title
document
Returns full URL of the HTML
3 URL
document.
Returns <body>, <img>
4 body, img
elements respectively.
Sr No Method Description
Writes HTML expressions or
1 write()
JavaScript code to a document.
Same as write(), but adds a
2 writeln() newline character after each
statement.
There are many ways of
accessing form elements, of
which the easiest is by
3 getElementById()
getElementById() method. In
which id property is used to find
an element.

The innerHTML Property


The innerHTML property is useful for getting html element and changing
its content.
The innerHTML property can be used to get or change any HTML element,
including <html> and <body>.
<!-- innerHTML property-->
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function changeText3()
{
var style="<h2 style='color:green'>";
var text="Welcome to the HTML5 and Javascript";
var closestyle="</h2>";
document.getElementById('para').innerHTML =style+text+closestyle;
}
</script></head>
<body style="backgroundcolor:cyan">
<h1 align="center">
<p id="para">Welcome to the site</p>
<input type="button"onclick="changeText3()" value="click this button to
change above text">
</h1>
</body>
</html>

Objects in Javascript are 1) Window 2)String


3)Math 4)Date 5)Number 6)Array

Window Object: 4 points


1. At the very top of the object hierarchy is the window object.
2. Window object is parent object of all other objects.
3. An object of window is created automatically by the browser.
4. Window object represents an open window in a browser

Windows Objects 4 properties and 9 Methods


Window Property : 1)Name 2)Location 3)Document 4)closed
Window Method : 1)alert() 2)confirm() 3)prompt() 4)open() 5)close()
6)blur() 7)focus() 8)print() 9)setTimeout()
Following table shows some of the methods and properties for window
object.
Sr
Property Description
No
1 name Sets or returns the name of a window.
2 location Returns the Location object for the window.
document Returns the Document object for the
3 Document
window.
Returns a Boolean value indicating whether a
4 closed
window has been closed or not.
Sr
Method Description
no
Displays the alert box containing message with ok
1 alert()
button.
Displays the confirm dialog box containing
2 confirm()
message with ok and cancel button.
Displays a dialog box to get input from the
3 prompt()
user.
4 open() Opens the new window.
5 close() Closes the current window.
6 blur() Removes focus from the current window.
7 focus() Sets focus to the current window.
8 print() Prints the content of current window.
Calls a function or evaluates an expression
9 setTimeout()
after a specified number of milliseconds.

3.4 JavaScript Event


keyboard events (onKeypress, onKeydown, onkeyup)
and mouse events (onClick, onMousemove, onMouseout, onMouseover).
Similarly, there are some more events used with form objects.
Input and other object Events:

Event Handler of Javascript (8 Events)


8 events : 1)onblur 2)onfocus 3)onchange 4)onselect 5)onsubmit
6)onreset 7)onload 8)onunload
Sr Event
Description
No handler
It occurs when user leaves field or
1 onblur
losses focus of an element.
2 onfocus It occurs when an element gets focus.
It occurs when user changes content
of an element or selects dropdown
3 onchange
value. E.g. for textbox, password,
select box, textarea etc.
It occurs when user selects some text
4 onselect
of an element.
It occurs when user clicks submit
5 onsubmit
button.
6 onreset It occurs when user clicks reset button.
It occurs when page/image has been
7 onload
loaded.
It occurs when document/page has
8 onunload
been unloaded or closes.
String Object:1 Property 8 Methods
String is used to store zero or more characters of text within single or double
quotes.
String object is used to store and manipulate text.

String Object Property : Length


String Object Method : 1)charAt() 2) indexOf() 3)lastIndexOf() 4)
lastIndexOf() 5) substr() 6) substring() 7) toLowerCase() 8)
toUpperCase()
Sr
N Property Description Example
o
<script>
document.write("<br>HELL
Returns the number of
1 length O INDIA".length); //length is
characters in a string
15
</script
Sr
Method Description Example
no
Returns the character at the document.write("HELLO
1 charAt() specified position (in INDIA".charAt(7));
Number). // Output 'N'
Returns the index of the
first occurence of specified
<script>
character in given string, or
document.write("HELLO
-1 if it never occurs, so
2 indexOf() INDIA".indexOf('N'));
with that index you can
// Output 7
determine if the string
</script>
contains the specified
character.
<script>
Returns the index of the document.write("HELLO
lastIndex
3 last occurence of specified INDIA!".lastIndexOf('I')); //
Of()
character in given string. Outputs 8
</script>
<script>
Returns the characters
document.write("HELLO
you specified: (14,7)
4 substr() INDIA!".substr(6, 5));//
returns 7 characters,
Output 'India '
from the 14th character.
</script>
substring Returns the characters you
5 <script>
() specified: (7,14) returns all
characters between the 7th
document.write("HELLO
and the 14th. INDIA!".substring(0, 11));//
Output 'India '
</script>
<script>
The trim() method document.write(" HELLO
6 trim() removes whitespace from INDIA!".trim());// Output
both sides of a string 'HELLO INDIA '
</script
<script>
document.write("HELLO
toLower Converts a string to lower
7 INDIA!".toLowerCase());//
Case() case
Output 'hello india'
</script>
<script>
document.write("hello
toUpperC Converts a string to upper
8 india!".toUpperCase());// Output
ase() case
'hello india'
</script>

Math Object : 9 Methods


The built-in Math object includes mathematical constants and functions. You
do not need to create the Math object before using it.
Following table contains list of 9 math object methods:
e.g. var x=56.899; alert(Math.ceil(x));

Math Object Method: 1)abs(x) 2)cbrt(x) 3)ceil(x) 4)floor(x) 5)max(x,y)


5)min(x,y) 6)pow(x,y) 7)random(x) 8)sqrt(x)
Sr
Method Description Example
No
x=-56.899;
Returns the absolute value alert(Math.abs(x));
1 abs(x)
of a number. Ans : 56.899
(removes minus sign)
x=125
Returns the cube root of a
2 cbrt(x) alert(Math.cbrt(x));
number.
Ans : 5
Returns the next integer
var x=56.899;
greater than or equal to
3 ceil(x) alert(Math.ceil(x));
a given number
Ans:57
(rounding up).
Returns the next integer
var x=56.899;
less than or equal to a
4 floor(x) alert(Math.floor(x));
given number (rounding
Ans:56
down).
Returns the highest-
max(x, y, alert(Math.max(1,2,3,4,5))
5 valued number in a list of
...) Ans : 5
numbers.
Returns the lowest-valued
min(x, y, alert(Math.min(1,2,3,4,5))
6 number in a list of
...) Ans : 1
numbers.
Returns the base to the
alert(Math.pow(5,2));
7 pow(x, y) exponent power, that is,
Ans : 25
xy.
Returns a random number
alert(Math.floor(Math.random()*10));
8 random(x) between 0 and 1
Ans 9
(including 0, but not 1).
Returns the square root of alert(Math.sqrt(25));
9 sqrt(x)
a number Ans :5

Date Object : 16 Methods


The date object is used to create date and time values.
Date Object is created using new keyword.
There are different ways to create new date object.
var currentdate=new Date();
var currentdate=new Date(milliseconds);
var currentdate=new Date(dateString);
var currentdate=new Date(year, month, day, hours, minute,
seconds,milliseconds);

Date Method : 1) getDate()2)getDay()3)getFullYear() 4)getHours()


5)getMinutes() 6)getMonth() 7)getSeconds() 8)getTime() 9)now()
10)setDate() 11)setFullYear() 12)setHours() 13)setMinutes()
14)setMonth() 15)setSeconds() 16)setTime()

Sr
N Method Description Example
o
<script>
Returns the day
document.write(new
1 getDate() of the month
Date().getDate());
(from 1-31)
</script>

Returns the day <script>


2 getDay() of the week document.write(new Date().getDay());
(from 0-6) </script>

<script>
getFullYe Returns the year document.write(new
3
ar() (four digits). Date().getFullYear());
</script>
<script>
Returns the hour document.write(new
4 getHours()
(from 0-23). Date().getHours());
</script>
<script>
Returns the
getMinute document.write(new
5 minutes (from 0-
s() Date().getMinutes());
59).
</script
<script>
Returns the
getMonth( document.write(new
6 month (from 0-
) Date().getMonth());
11).
</script>
<script>
Returns the
getSecond document.write(new
7 seconds (from 0-
s() Date().getSeconds());
59).
</script>
Returns the <script>
number of document.write(new
8 getTime() milliseconds Date().getTime());
since midnight </script>
Jan 1, 1970. (Ans in milliseconds)
Returns the
<script>
number of
document.write(Date.now());
9 now() milliseconds
</script>
since midnight
(Ans in milliseconds)
Jan 1, 1970.
<script>
Sets the day of
let date = new Date();
10 setDate() the month of a
date.setDate(15); document.write(date);
date object.
</script>
setFullYea Sets the full year
11 <script>
r() of a date object.
let date = new Date();
date.setFullYear(2025);
document.write(date);
</script>
<script>
Sets the hours of let date = new Date();
12 setHours()
a date object. date.setHours(10); document.write(date);
</script>
<script>
setMinute Set the minutes let date = new Date();
13
s() of a date object. date.setMinutes(30); document.write(date);
</script>
<script>
setMonth( Sets the month let date = new Date();
14
) of a date object. date.setMonth(10); document.write(date);
</script>
<script>
setSecond Sets the seconds let date = new Date();
15
s() of a date object. date.setSeconds(45); document.write(date);
</script>
Sets a date to a
specified
let date = new Date();
number of
16 setTime() date.setTime(1634567890123);
milliseconds
document.write(date);
after/before Jan
1, 1970.
Number Object : 3 Property 4 Method
It helps us to work with numbers.
Primitive values (like 34 or 3.14) cannot have properties and methods, but
with JavaScript it is available with primitive values.

Number Object Property : 1)MIN_VALUE 2)MAX_VALUE 3) NaN


Number Methods :1)isInteger() 2)parseFloat() 3)parseInt() 4)isFixed()
Sr Examples
Property Description
No
<script>
document.write(N
Returns the largest minimum
1 MIN_VALUE umber.MIN_VAL
value.
UE);
</script>
<script>
Returns the largest maximum document.write(N
2 MAX_VALUE
value. umber.MAX_VA
LUE);
</script>
<script>
It represents ‘Not a Number’ document.write(N
3 NaN
value. aN);
</script>
Sr
Method Description
No
<script>
document.write(N
It returns the string that represents
umber.isInteger(10
1 isInteger() a number with exact digits after a
));
decimal point
</script>
Ans : True
<script>
It converts the given string into document.write(pa
2 parseFloat()
a floating point number. rseFloat("10.5"));
</script>
<script>
It converts the given string into document.write(pa
3 parseInt()
a integer number. rseInt("10"));
</script>
<script>
It returns the string that represents document.write((1
4 isFixed() a number with exact digits after a 0.5678).toFixed(2)
decimal point. );
</script>

Array Object 5 points


1. JavaScript arrays are used to store multiple values in single
variable.
2. An array is a special variable which can hold more than one
value at a time.
3. Arrays become really useful when you need to store large
amounts of data of the same type. You can create an array in
JavaScript as given below.
var fruits=["Mango","Apple","Orange","Grapes"];
OR
var fruits=new Array("Mango","Apple","Orange","Grapes");
4. You can access and set the items in an array by referring to its
indexnumber and the index of the first element of an array is
zero. arrayname[0] is the first element, arrayname[1] is second
element and so on. e.g. var fruitname=fruits[0];
5. document.getElementById("demo").inner HTML=fruits[1];
Array Object : 2 Property 10 Methods
Array Object Property: 1) index 2) length
Array Object Method: 1)concat 2)copywithin 3)find() 4)forEach()
5)indexOf() 6)isArray() 7)pop() 8)push() 9)reverse() 10)sort()

Sr Prop
Description
No erty
<script>
document.write
The property represents the zero-based
1 index ([1, 2, 3, 4,
index of the match in the string
5].indexOf(3));
</script>
<script>
document.write
2 length Reflect number of elements in array. ([1, 2, 3, 4,
5].length);
</script>
Sr Meth Example
Description
No od Program
<script>
document.writ
concat Joins two or more arrays, and returns e([1, 2,
1
() a copy of the joined arrays 3].concat([4, 5,
6]));
</script>
document.write
copy
Copies array elements within the array, ([1, 2, 3, 4,
2 Within
to and from specified positions. 5].copyWithin(
()
0, 3));
<script>
document.write
([1, 2, 3, 4,
Returns the value of the first element in 5].find(element
3 find()
an array that satisfies a test in testing. => element >
3))
</script>
Ans : 4
<script>
[1, 2, 3, 4,
5].forEach(ele
forEac
4 Calls a function for each array element. ment =>
h()
document.write
(element));
</script>
<script>
document.writ
index Search the array for an element and
5 e([1, 2, 3, 4,
Of() returns its position.
5].indexOf(3));
</script>
<script>
document.write
isArra
6 Checks whether an object is an array. (Array.isArray(
y()
[1, 2, 3]));
</script>
<script>
document.writ
Removes the last element of an array,
7 pop() e([1, 2, 3, 4,
and returns that element.
5].pop());
</script>
<script>
document.writ
Adds new elements to the end of an
8 push() e([1, 2, 3,
array, and returns the new length
4].push(5));
</script>
<script>
document.write
revers Reverses the order of the elements in an
9 ([1, 2, 3, 4,
e() array.
5].reverse());
</script>
<script>
document.write
([5, 3, 8, 1,
10 sort() Sorts the elements of an array.
2].sort((a, b) =>
a - b));
</script>

Summary
JavaScript is light weight scripting language.
JavaScript is platform independent language.
There are two types of scripts; client side script and server side scripts.
Client side
scripts reside on client machine and server side script resides on web
server.
JavaScript provide ‘switch…case’ as multi way decision statement.
For....loop, while…loop and do…while are commonly used looping
structures in JavaScript.
DOM (Document Object Model) is a programming interface for HTML
and XML documents. It defines logical structure of document.
Window object is parent object of all other objects hence its methods
can be used without specifying it.
JavaScript is event based language support objects events such as
onBlur, onFocus, onChange, onSelect, onSubmit, onLoad, onUnload,
onResize etc.
JavaScript supports built-In objects such as Date, String, Math, Number
and array etc.
These objects contain number of properties and methods that are useful
while creating interacting web pages.
Note : islnteger() is supported by version Mozilla Firefox 16 and higher.

Journal Program

Practical 8 from Journal


Create a web page in HTML having a white background and two
Button Objects. Write code using JavaScript such that when the mouse
is placed over the first button object without clicking, the color of the
background of the page should change after every __ seconds. There
should at least be 7 different and visibly distinct background colors
excluding the default color. When the second button object is clicked,
appropriate message should be displayed in Browsers status bar.
Create another web page using JavaScript where the background color
changes automatically after every ___ seconds. This event must be
triggered automatically after the page gets loaded in the browser. There
should at least be 7 different and visibly distinct background colors.
When the page is unloaded, the appropriate alert message should be
displayed.

Ans 8 Coding --> Filename: Color.html


<!-- Filename color.html-->
<!DOCTYPE html>
<html>
<title> Display of 7 different Colors </title>
<script> function f1()
{
document.bgColor="red";
window.setTimeout("f2()",1200);
}
function f2()
{
document.bgColor="yellow";
window.setTimeout("f3()",1200);
}
function f3()
{
document.bgColor="brown";
window.setTimeout("f4()",1200);
}
function f4()
{
document.bgColor="green";
window.setTimeout("f5()",1200);
}
function f5()
{
document.bgColor="purple";
window.setTimeout("f6()",1200);
}
function f6()
{
document.bgColor="pink";
window.setTimeout("f7()",1200);
}
function f7()
{
document.bgColor="blue";
window.setTimeout("f1()",1200);
}
function msg()
{
windows.status="Display of 7 different colors";
}
</script>
<body align=center>
<form>
<input type="button" value="colors" name="b1"
onMouseover="f1()"> <br>
<input type="button" value="message" name="b2"
onClick="msg()">
</form>
</body>
</html>

Practical 8 Output
Practical 8
Coding --> Filename: Color1.html
<!-- Filename Color1.html-->
<!DOCTYPE html>
<html>
<title>
Display of 7 different Colors
</title>
<script> function f1()
{
document.bgColor="red";
window.setTimeout("f2()",1200);
}
function f2()
{
document.bgColor="yellow";
window.setTimeout("f3()",1200);
}
function f3()
{
document.bgColor="brown";
window.setTimeout("f4()",1200);
}
function f4()
{
document.bgColor="green";
window.setTimeout("f5()",1200);
}
function f5()
{
document.bgColor="purple";
window.setTimeout("f6()",1200);
}
function f6()
{
document.bgColor="pink";
window.setTimeout("f7()",1200);
}
function f7()
{
document.bgColor="skyblue";
window.setTimeout("f1()",1200);
}
function msg()
{
alert("Display of colors page closed by user");
}
</script>
<body onload="f1()" onUnload="msg()">
<h1 align=center>
Display of 7 Different colors on load event</h1>
</body>
</html>

Practical 8 Output

Practical 9 Question
Create event driven JavaScript program for the following. Make use
of appropriate variables, JavaScript inbuilt string functions and
control structures. To accept string from user and count number of
vowels in the given string.
Practical 9 Ans
Coding Filename: vowel.html
Ans
<!-- File name vowel.html-->
<!DOCTYPE html>
<html>
<head>
<title>Vowel Count </title>
</head>
<body>
<form name="form1">
<h1> Enter the String whose vowel will be counted</h1>
<input type="text" name="text1">
<input type="button" name="vowel" value="Click to count"
onclick=count()>
</form>
<script>
function count()
{
var i,ch,str,counter=0;
str=form1.text1.value;
for(i=0;i<str.length;i++)
{
ch=str.charAt(i);
if(ch=='A'||ch=='a'||ch=='E'||ch=='e'||ch=='I'||ch=='i'||ch=='O'||ch=='o'||
ch=='U'||ch=='u')
counter++;
}
alert("Number of Vowels in Entered String is : "+counter);
}
</script>
</html>
Practical 9 Output

Practical 10 Question
Create JavaScript program which compute the average marks of
students. Accept six subject marks of student from user. Calculate
average marks of student which is used to determine the
corresponding grades.

Range Grade
35 to 60 F
61 to 70 D
71 to 80 C
81 to 90 B
91 to 100 A

Practical 10 : Ans :
<!-- Filename Grade.html-->
<!DOCTYPE html>
<html>
<head>
<title> Student Grade </title>
</head>
<body>
<h2 align="center"> Student Grade </h2>
<form name="frm1">
Enter Marks of English : <input type="number" name="t1"><br><br>
Enter Marks of Maths : <input type="number" name="t2"><br><br>
Enter Marks of Physics : <input type="number" name="t3"><br><br>
Enter Marks of Chemistry : <input type="number" name="t4"><br><br>
Enter Marks of Biology : <input type="number" name="t5"><br><br>
Enter Marks of I.T : <input type="number" name="t6"><br><br>
<input type="button" name="bt1" value="Get Grade" onClick="grade()">
</form>
<body>
<script>
function grade()
{
var s1,s2,s3,s4,s5,s6,total,avg;
s1=parseInt(frm1.t1.value)
s2=parseInt(frm1.t2.value)
s3=parseInt(frm1.t3.value)
s4=parseInt(frm1.t4.value)
s5=parseInt(frm1.t5.value)
s6=parseInt(frm1.t6.value)
total=s1+s2+s3+s4+s5+s6;
avg=total/6;
alert("Total Marks of the Student is : "+total);
alert("Average Marks of the Student is : "+avg);

if(avg<60)
{
alert("Grade F");
}
else if(avg<70)
{
alert("Grade D");
}
else if(avg<80)
{
alert("Grade C");
}
else if(avg<90)
{
alert("Grade B");
}
else if(avg<=100)
{
alert("Grade A");
}
else
{
alert("Incorrect Entry")
}
}
</script>
</html>
Practical 10 Output

FILL IN THE BLANKS


1. _______script resides on server computer.
Ans: Server Side

2. _______statement is used to jump out of loop.


Ans: Break

3. _______ defines logical structure of document.


Ans: DOM (Document Object Model)

4._______property of window object returns Boolean value


indicating whether window is closed or not.
Ans: Closed

5………..event occurs when an element looses its focus.


Ans: onblur
TRUE OR FALSE
1. JavaScript is case sensitive language.
Ans : True

2. Math.ceil() function is used to return the nearest integer less


than or equal to given number.
Ans: False

3. MAX_VALUE property of number object returns smallest


possible value.
Ans: False

4. getDay() method of Date object returns month in number.


Ans: False

5. onKeydown event occurs when user moves mouse pointer.


Ans: False

6. car.name=Ferrari in this example car is an object name.


Ans: True

7. getElementById is the correct method of DOM object.


Ans: True

8 Javascript has a bulit-in multiway decision statement as LOOP.


Ans: True

MCQ ONE CORRECT ANSWER


1. JavaScript is ____language.
a) Compiled b) Interpreted c) Both a and b d) None of the above
Ans: b)Interpreted

2. Select correct method name of String object_____


a) charAt() b) characterAt() c) valueAt() d) lengthAt()
Ans: d) lengthAt()

3. ____ method displays message box with Ok and Cancel button.


a) Confirm() b) Alert() c) both a and b d) None of these
Ans: a) Confirm()
4. We can declare all types of variables using keyword _____
a) var b) dim c) variable d) declare
Ans: a) var

5. Trace ouput of following JavaScript code.


var str="InformationTechnology";
document.write(str. lastIndexOf("o");
a) 18 b) 19 c) 20 d) 21
Ans: a) 18

5. In Javascript…… statement is used to jump out of loop


a) Join b) break c) Leave d)Check
Ans: a) break

MCQ TWO CORRECT ANSWER


1. Valid two methods of Date object are ___and ___
a) setTime() b) getValidTime() c) getTime() d) setValidTime()
Ans: a) setTime() c) getTime()

2. Properties of document object are ___ and ______


a) URL b) title c) name d)status
Ans: a) URL b) title

3. ___ and ____are event /event handler used with text object in
JavaScript.
a)onBlur b) onMove c)onFocus d) onAction
Ans : a)onBlur c)onFocus

4. Select two correct methods of window object __ __ ___


a) write() b) check() c) writeln() d) close() e) open() f) charAt()
Ans : d) close() e) open()

5. Select two correct methods of window object __ __ ___


a) write() b) alert() c) focus() d) lost() e) gain() f) charAt()
Ans : b) alert() c) focus

6. JavaScript features are ____ ____ and _____


a) supports event-based facilities
b) is platform dependent language
c) case insensitive scripting language
d) provide inbuilt objects
e) requires special software to run
Ans : a) supports event-based facilities d) provide inbuilt
objects

7. Inbuilt objects in JavaScript are ____, _____and____


a) Time b) Date c) Inheritance d) Array e) Number f) function
Ans: b) Date e) Number

8. Inbuilt objects in JavaScript are ____, _____and____


a) Time b) Math c) Inheritance d) Array e) Number f) function
Ans : b) Math d) Array

9. Inbuilt objects in JavaScript are ____, _____and____


a) Time b) Window c) Inheritance d) String e) Number f)
function
Ans : b) Window d) String

10. The scope of variable can be______ _____ and _______


a) local b) global c) universal d) static e) final f) outside
Ans : a) local d) global

MATCH THE FOLLOWING


A B (All Correct Answers)
Returns the next integer less than or equal
ceil()
to given number.
Returns next integer greater than or equal
floor()
to to given number.
Writes HTML expression or javascript code to
write()
a document
focus() Sets focus to current window
Removes white spaces from both sides of
trim()
string.

MARKS DISTRIBUTION
Chapter 3 Advance Javascript marks distribution
Q.Type A.JS
Q1 FiB 2
Q2 T/F 2
Q3 MCQ1 1
Q4 MCQ2 4
Q5 MCQ3 0
Q6 match 1
Q7 short
10
Q8 prg 5 or 5
15

You might also like