Professional Documents
Culture Documents
ENGINEERING COLLEGE
(An Autonomous Institution, Affiliated to Anna University, Chennai)
Sevalpatti (P.O), Sivakasi– 626140
VI Semester
Open Elective
Prepared By,
Dr.S.Priyadarsini, ASP/CSE
Mrs.K.Kirubananthavalli, AP/CSE
Ms.P.Rajalakshmi, AP/CSE
2
JavaScript, Data types and Variables - Variables, Strings, Booleans, Arrays, Objects, Basics of
HTML - Tags and Elements, HTML Hierarchy.
HTML TAGS
HTML stands for Hyper Text Markup Language.
HTML is used to create web pages and web applications.
Tim Berners-Lee is known as the father of HTML. The first available description of HTML
was a document called "HTML Tags" proposed by Tim in late 1991.
The latest version of HTML is HTML5.
Hyper Text: Hyper Text simply means "Text within Text." A text has a link within it, is a
hypertext. Hyper Text is a way to link two or more web pages (HTML documents) with each
other.
Markup language: A markup language is a computer language that is used to apply layout
and formatting conventions to a text document. Markup language makes text more interactive
and dynamic. It can turn text into images, tables, links, etc.
Features of HTML
It is a very easy and simple language. It can be easily understood and modified.
It is very easy to make an effective presentation with HTML.
It is a markup language, so it provides a flexible way to design web pages along with the
text.
It facilitates programmers to add a link on the web pages (by html anchor tag), so it enhances
the interest of browsing of the user.
It is platform-independent because it can be displayed on any platform like Windows,
Linux, and Macintosh, etc.
It facilitates the programmer to add Graphics, Videos, and Sound to the web pages which
makes it more attractive and interactive.
HTML is a case-insensitive language, which means we can use tags either in lower-case or
upper-case.
Example
<!DOCTYPE>
<html>
<head>
3
<title>Web page title</title>
</head>
<body>
<h1>Write Your First Heading</h1>
<p>Write Your First Paragraph.</p>
</body>
</html>
• <!DOCTYPE> - it instructs the browser about the version of HTML.
• <html > tag informs the browser that it is an HTML document. Text between html tag
describes the web document.
• <head> - First element inside the <html> element, which contains the metadata (information
about the document). It must be closed before the body tag opens.
• <title>: As its name suggested, it is used to add title of that HTML page which appears at the
top of the browser window.
• <body> : Text between body tag describes the body content of the page that is visible to the
end user. This tag contains the main content of the HTML document.
• <h1> : Text between <h1> tag describes the first level heading of the webpage.
<html>
<head>
<title>Title of your web page</title>
</head>
<body>HTML web page contents </body>
</html>
HTML headings
There are six different HTML headings which are defined with the <h1> to <h6> tags, from
highest level h1 (main heading) to the least level h6 (least important heading).
<!DOCTYPE html>
<html>
<body>
<h1>Heading no. 1</h1>
<h2>Heading no. 2</h2>
HTML paragraph
HTML p tag is used to define a paragraph in a webpage.
<!DOCTYPE html>
<html>
<body>
<p>This is first paragraph.</p>
<p>This is second paragraph.</p>
<p>This is third paragraph.</p>
</body>
</html>
Output
This is first a paragraph.
This is second paragraph.
This is a third paragraph.
HTML <br> Tag
An HTML <br> tag is used for line break and it can be used with paragraph elements.
<!DOCTYPE html>
<html>
<body>
5
<h1>The br element</h1>
<p>To force<br> line breaks<br> in a text,<br> use the br<br> element.</p>
</body> </html>
Output
The br element
To force
line breaks
in a text,
use the br
element.
HTML Anchor
The HTML anchor tag defines a hyperlink that links one page to another page. It can create
hyperlink to other web page as well as files, location, or any URL. The "href" attribute is the
most important attribute of the HTML a tag. and which links to destination page or URL.
!DOCTYPE>
<html>
<body>
<a href="second.html">Click for Second Page</a>
</body>
</html>
• HTML img tag is used to display image on the web page. HTML img tag is an empty tag
that contains attributes only, closing tags are not used in HTML image element.
<!DOCTYPE>
<html>
<body>
<h2>HTML Image Example</h2>
<img src="good-morning.jpg" alt="Good Morning Friends"/>
</body>
</html>
6
<!DOCTYPE html>
<html>
<head>
<title>Image tag</title>
</head>
<body>
<h2>HTML image example with height and width</h2>
<img src="https://static.javatpoint.com/htmlpages/images/animal.jpg"
height="180" width="300" alt="animal image">
</body>
</html>
HTML table tag is used to display data in tabular form (row * column).
There can be many columns in a row.
We can create a table to display data in tabular form, using <table> element, with the help of
<tr> , <td>, and <th> elements.
In Each table, table row is defined by <tr> tag, table header is defined by <th>, and table data
is defined by <td> tags.
7
<!DOCTYPE>
<html>
<body>
<table border="8">
<tr><th>First_Name</th><th>Last_Name</th><th>Marks</th></tr>
<tr><td>Sonoo</td><td>Jaiswal</td><td>60</td></tr>
<tr><td>James</td><td>William</td><td>80</td></tr>
<tr><td>Swati</td><td>Sironi</td><td>82</td></tr>
<tr><td>Chetna</td><td>Singh</td><td>72</td></tr>
</table>
</body>
</html>
HTML Lists
HTML Lists are used to specify lists of information.
All lists may contain one or more list elements.
There are three different types of HTML lists:
o Ordered List or Numbered List (ol)
o Unordered List or Bulleted List (ul)
o Description List or Definition List (dl)
HTML Ordered List or Numbered List
In the ordered HTML lists, all the list items are marked with numbers by default.
It is known as numbered list also.
The ordered list starts with <ol> tag and the list items start with <li> tag.
8
<!DOCTYPE>
<html>
<body>
<ol>
<li>Aries</li>
<li>Bingo</li>
<li>Leo</li>
<li>Oracle</li>
</ol>
</body>
</html>
Output
Output:
9
Unordered List with Disc Bullets
Coffee
Tea
Milk
HTML Description Lists
HTML also supports description lists.
A description list is a list of terms, with a description of each term.
The <dl> tag defines the description list, the <dt> tag defines the term (name), and the <dd>
tag describes each term:
Program:
<!DOCTYPE html>
<html>
<body>
<h2>A Description List</h2>
<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>
</body>
</html>
Output:
Description List
Coffee
- black hot drink
Milk
- white cold drink
Whitespace in HTML and Block-Level Elements
Hello world!
My first web page.
Let's add another paragraph.
10
Output:
HTML, all whitespace is collapsed into a single space. Whitespace means any character that
results in blank space on the page
Any blank lines insert between two pieces of text in an HTML document collapsed into a
single space.
The p and h1 elements are called block-level elements because they display their content in a
separate block, starting on a new line, and with any following content on a new line.
Inline Elements
Add two more elements to our document, em and strong
Em - element makes its content italic. The strong element makes its content bold.
The em and strong elements are both inline elements, which means that they don’t put their
content onto a new line, as block-level elements do.
<!DOCTYPE html>
<html>
<body>
<h1>Hello world!</h1>
<p>My <em>first</em> <strong>web page</strong></p>
<p>Let's add another <strong><em>paragraph</em></strong></p>
</body>
</html>
Output
Hello world!
My first web page.
Let's add another paragraph.</p
HTML Hierarchy
The top element is the html element. It contains the head and body elements. The head
contains the title element, and the body contains the h1 and p elements.
The browser interprets HTML according to this hierarchy.
11
JavaScript-Introduction
JavaScript programming language is used to write programs that run in web pages.
JavaScript can control how a web page looks or make the page respond when a viewer clicks
a button or moves the mouse.
Sites like Gmail, Facebook, and Twitter use JavaScript to make it easier to send email, post
comments, or browse web sites.
JavaScript play music and create amazing visual effects. For example, music video created by
HelloEnjoy for Ellie Goulding’s song “Lights” - http://lights.helloenjoy.com
JavaScript build tools for others to make their own art. Patatap (http://www.patatap.com/) is a
kind of virtual “drum machine” that creates all kinds of cool noises—and cool animations .
JavaScript play fun games. CubeSlam (https://www .cubeslam.com/) is a 3D re-creation of
the classic game .
It’s an easier to learn than many other programming languages.
In order to write and run JavaScript programs, we need is a web browser like Internet
Explorer, Mozilla Firefox, or Google Chrome.
JavaScript Data Types and Variables
In JavaScript, there are three basic types of data: numbers, strings, and Booleans.
A JavaScript variable can hold any type of data.
12
JavaScript has dynamic types. This means that the same variable can be used to hold different
data types:
let x;
x = 5;
x = "John";
Example
var x = 5;
var y = 6;
var z = x + y;
Program
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Variables</h2>
<p>In this example, x, y, and z are variables.</p>
<p id="demo"></p>
<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo"). innerHTML = "The value of z is: " + z;
</script>
</body>
</html>
Output
JavaScript Variables
In this example, x, y, and z are variables.
The value of z is: 11
JavaScript Strings
Strings store text. Strings are written inside quotes. we can use single or double quotes:
Example
var carname = "Volvo XC60"; // Double quotes
var carname = 'Volvo XC60'; // Single quotes
13
The length of a string is found in the built in property length:
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
Program
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strings</h2>
<p>Strings are written inside quotes. You can use single or double quotes:</p>
<p id="demo"></p>
<script>
var carName1 = "Volvo XC60"; // Double quotes
var carName2 = 'Volvo XC60'; // Single quotes
document.getElementById("demo").innerHTML =
carName1 + " " + carName2;
</script>
</body>
</html>
Output
JavaScript Strings
Strings are written inside quotes. You can use single or double quotes:
Volvo XC60 Volvo XC60
The length of a string is found in the built in property length:
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
Program
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Properties</h2>
<p>The length property returns the length of a string:</p>
<p id="demo"></p>
<script>
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
14
document.getElementById("demo").innerHTML = txt.length;
</script>
</body>
</html>
Output
JavaScript String Properties
The length property returns the length of a string:
26
Cutting Up Strings
The slice() method extracts a part of a string. It returns the extracted part in a new string.
It does not change the original string.
The start and end parameters specifies the part of the string to extract.
The first position is 0, the second is 1,
A negative number selects from the end of the string.
Program
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The slice() Method</h2>
<p>slice() extracts a part of a string and returns the extracted part:</p>
<p id="demo"></p>
<script>
let text = "Hello world!";
let result = text.slice(0, 5);
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
Output
JavaScript Strings
The slice() Method
slice() extracts a part of a string and returns the extracted part:
Hello
15
Changing Strings to All Capital or All Lowercase Letters
toLowerCase() - converts a string to lowercase letters.
toUpperCase() - converts a string to uppercase letters.
Program
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>To toUpperCase() Method</h2>
<p>toUpperCase() converts a string to uppercase letters:</p>
<p id="demo"></p>
<script>
let text = "Hello World!";
let result = text.toUpperCase();
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html> <!DOCTYPE html>
Output
JavaScript Strings
To toUpperCase() Method
toUpperCase() converts a string to uppercase letters:
HELLO WORLD!
Program
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The toLowerCase() Method</h2>
<p>toLowerCase() converts a string to lowercase letters:</p>
<p id="demo"></p>
<script>
let text = "Hello World!";
let result = text.toLowerCase();
16
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
Output
JavaScript Strings
The toLowerCase() Method
toLowerCase() converts a string to lowercase letters:
hello world!
JavaScript Numbers
All JavaScript numbers are stored as decimal numbers (floating point).
o let x1 = 34.00; // With decimals:
o let x2 = 34; // Without decimals:
Exponential Notation
Extra large or extra small numbers can be written with scientific (exponential) notation:
Example
let y = 123e5; // 12300000
let z = 123e-5; // 0.00123
JavaScript has only one type of number. Numbers can be written with or without decimals.
Example
var x = 3.14; // A number with decimals
var y = 3; // A number without decimals
Program
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Numbers</h2>
<p>Numbers can be written with or without decimals:</p>
<p id="demo"></p>
<script>
var x = 3.14;
var y = 3;
17
document.getElementById("demo").innerHTML = x + "<br>" + y;
</script>
</body>
</html>
Output
JavaScript Numbers
Numbers can be written with or without decimals:
3.14
3
JavaScript Booleans
A JavaScript Boolean represents one of two values: true or false.
Program:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Booleans</h1>
<p>Display the value of Boolean(10 > 9):</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Boolean(10 > 9);
</script>
</body>
</html>
Output:
JavaScript Booleans
Display the value of Boolean(10 > 9):
True
Comparisons and Conditions
== equal to if (day == "Monday")
> greater than if (salary > 9000)
< less than if (age < 18)
The Boolean value of -0 (minus zero) is false
18
Program:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Booleans</h1>
<p>Display the Boolean value of -0:</p>
<p id="demo"></p>
<script>
let x = -0;
document.getElementById("demo").innerHTML = Boolean(x);
</script>
</body>
</html>
Output:
JavaScript Booleans
Display the Boolean value of -0:
False
JavaScript Operators
JavaScript you perform basic mathematical operations like addition, subtraction,
multiplication, and division. we use the symbols +, -, *, and /, which are called
operators.
Types of JavaScript Operators
o Arithmetic Operators
o Assignment Operators
o Comparison Operators
o String Operators
o Logical Operators
o Bitwise Operators
o Ternary Operators
o Type Operators
19
Arithmetic Operators
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arithmetic</h1>
<h2>Arithmetic Operations</h2>
<p>A typical arithmetic operation takes two numbers (or expressions) and produces a
new number.</p>
<p id="demo"></p>
<script>
let a = 3;
let x = (100 + 50) * a;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
Output
JavaScript Arithmetic
Arithmetic Operations
A typical arithmetic operation takes two numbers (or expressions) and produces a new number.
450
Comparison and Logical Operators
Comparison and Logical operators are used to test for true or false.
Operator Description Comparing Returns
== equal to x == 8 false
!= not equal x != 8 true
> greater than x>8 false
< less than x<8 true
>= greater than or equal to x >= 8 false
<= less than or equal to x <= 8 true
20
Program:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Comparison</h1>
<h2>The == Operator</h2>
<p>Assign 5 to x, and display the value of the comparison (x == 8):</p>
<p id="demo"></p>
<script>
let x = 5;
document.getElementById("demo").innerHTML = (x == 8);
</script>
</body>
</html>
Output:
JavaScript Comparison
The == Operator
Assign 5 to x, and display the value of the comparison (x == 8):
False
Logical Operators
Operator Description Example
&& and (x < 10 && y > 1)
|| or (x == 5 || y == 5)
! not! (x == y)
Program:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Comparison</h1>
<h2>The && Operator (Logical AND)</h2>
21
<p>The && operator returns true if both expressions are true, otherwise it returns
false.</p>
<p id="demo"></p>
<script>
let x = 6;
let y = 3;
document.getElementById("demo").innerHTML =
(x < 10 && y > 1) + "<br>" +
(x < 10 && y < 1);
</script>
</body>
</html>
Output:
JavaScript Comparison
The && Operator (Logical AND)
The && operator returns true if both expressions are true, otherwise it returns false.
true
false
Incrementing and Decrementing
Increasing by 1 is called incrementing, and decreasing by 1 is called decrementing.
Increment using the operator ++ , decrement using the operators--.
Program:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arithmetic</h1>
<h2>The ++ Operator</h2>
<p id="demo"></p>
<script>
let x = 5;
x++;
let z = x;
document.getElementById("demo").innerHTML = z;
22
</script>
</body>
</html>
Output:
JavaScript Arithmetic
The ++ Operator
6
Program:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arithmetic</h1>
<h2>The -- Operator</h2>
<p id="demo"></p>
<script>
let x = 5;
x--;
let z = x;
document.getElementById("demo").innerHTML = z;
</script>
</body>
</html>
Output:
JavaScript Arithmetic
The -- Operator
4
JavaScript Assignment Operators
Operator Example Same As
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
23
/= x /= y x=x/y
%= x %= y x=x%y
**= x **= y x = x ** y
Program:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Assignments</h1>
<h2>Addition Assignment</h2>
<h3>The += Operator</h3>
<p id="demo"></p>
<script>
let x = 10;
x += 5;
document.getElementById("demo").innerHTML = "Value of x is: " + x;
</script>
</body> </html>
Output:
JavaScript Assignments
Addition Assignment
The += Operator
Value of x is: 15
JavaScript Objects
Objects in JavaScript are very similar to arrays, but objects use strings instead of numbers to
access the different elements.
The strings are called keys or properties, and the elements they point to are called values.
These pieces of information are called key-value pairs. While arrays are mostly used to
represent lists of multiple things, objects are often used to represent single things with multiple
characteristics, or attributes.
JavaScript variables are containers for data values.
The following code assigns a simple value (Fiat) to a variable named car:
24
var car = "Fiat";
Program
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Variables</h2>
<p id="demo"></p>
<script>
// Create and display a variable:
var car = "Fiat";
document.getElementById("demo").innerHTML = car;
</script>
</body>
</html>
Output
JavaScript Variables
Fiat
Create an object:
Objects are variables too. But objects can contain many values.
var cat = {
"legs": 3,
"name": "Harmony",
"color": "Tortoiseshell"
};
we create a variable called cat and assign an object to it with three key value pairs.
To create an object, we use curly brackets, {}, instead of the straight brackets we used to
make arrays.
The curly brackets and everything in between them are called an object literal.
An object literal is a way of creating an object by writing out the entire object at once.
The following code assigns many values (Fiat, 500, white) to a variable named car:
25
var car = {type:"Fiat", model:"500", color:"white"};
Program
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
// Create an object:
var car = {type:"Fiat", model:"500", color:"white"};
// Display some data from the object:
document.getElementById("demo").innerHTML = "The car type is " + car.type;
</script>
</body>
</html>
Output
JavaScript Objects
The car type is Fiat
JavaScript Arrays
JavaScript arrays are used to store multiple values in a single variable.
To create an array with values in it, enter the values, separated by commas, between the
square brackets.
Individual values in an array is called items or elements.
Example
var cars = ["Saab", "Volvo", "BMW"];
Program
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
26
<p id="demo"></p>
<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
</body>
</html>
Output
JavaScript Arrays
Saab,Volvo,BMW
Accessing an Array’s Elements
access an array element by referring to the index number
Program:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>Bracket Indexing</h2>
<p>JavaScript array elements are accessed using numeric indexes (starting from
0).</p>
p id="demo"></p>
<script>
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
</script>
</body>
</html>
Output:
JavaScript Arrays
Bracket Indexing
JavaScript array elements are accessed using numeric indexes (starting from 0).
Saab
Changing an Array Element
<!DOCTYPE html>
27
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>Bracket Indexing</h2>
Output:
JavaScript Arrays
The length Property
The length property sets or returns the number of elements in an array.
Banana,Orange
Add a new item to an array
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
Program:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The push() Method</h2>
<p>push() adds new items to the end of an array:</p>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
document.getElementById("demo").innerHTML = fruits;
</script>
</body>
</html>
Output:
JavaScript Arrays
The push() Method
push() adds new items to the end of an array:
Banana,Orange,Apple,Mango,Kiwi
Removing Elements from an Array
29
The pop() method removes the last element from an array:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();
Program:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The pop() Method</h2>
<p>The pop() method removes the last element from an array.</p>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
fruits.pop();
document.getElementById("demo2").innerHTML = fruits;
</script>
</body>
</html>
Output:
JavaScript Arrays
The pop() Method
The pop() method removes the last element from an array.
Banana,Orange,Apple,Mango
Banana,Orange,Apple
Finding the Index of an Element in an Array
To find the index of an element in an array, use .indexOf(element).
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
30
<h2>The indexOf() Method</h2>
<p>indexOf() returns the position of a specified value in an array:</p>
<p id="demo"></p>
<script>
Math.floor()
This method rounds a number DOWN to the nearest integer.
Program
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Math</h1>
<h2>The Math.floor() Method</h2>
<p>Math.floor() rounds a number DOWN to the nearest integer:</p>
<p id="demo"></p>
<script>
let a = Math.floor(0.60);
let b = Math.floor(0.40);
let c = Math.floor(5);
let d = Math.floor(5.1);
let e = Math.floor(-5.1);
let f = Math.floor(-5.9);
document.getElementById("demo").innerHTML =
a + "<br>" + b + "<br>" + c + "<br>" + d + "<br>" + e + "<br>" + f;
</script>
</body>
</html>
Output
JavaScript Math
The Math.floor() Method
Math.floor() rounds a number DOWN to the nearest integer:
0
0
5
5
32
-6
-6
33
JavaScript Can Change HTML Attribute Values
In this example JavaScript changes the value of the src (source) attribute of an
<img> tag:
Program
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can change HTML attribute values.</p>
<p>In this case JavaScript changes the value of the src (source) attribute of an
image.</p>
<button onclick="document.getElementById('myImage').src='img_bulbon.gif'">Turn
on the light</button> <img id="myImage" src="img_bulboff.gif"
style="width:100px">
<button onclick="document.getElementById('myImage').src='img_bulboff.gif'">Turn off the
light</button>
</body>
</html>
Output
34
What Can JavaScript Do?
JavaScript can change HTML attribute values.
In this case JavaScript changes the value of the src (source) attribute of an image.
35
JavaScript Can Change HTML Styles (CSS)
Changing the style of an HTML element, is a variant of changing an HTML attribute:
Example
document.getElementById("demo").style.fontSize = "35px";
or
document.getElementById('demo').style.fontSize = '35px';
Program
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change the style of an HTML element.</p>
<button type="button"
onclick="document.getElementById('demo').style.fontSize='35px'">Click
Me!</button>
</body>
</html>
Output
36
JavaScript Can Hide HTML Elements
Hiding HTML elements can be done by changing the display style:
document.getElementById("demo").style.display = "none";
or
document.getElementById('demo').style.display = 'none';
Program
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can hide HTML elements.</p>
<button type="button"
onclick="document.getElementById('demo').style.display='none'">Click
Me!</button>
</body>
</html>
Output
37
or
document.getElementById('demo').style.display = 'block';
Program
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can show hidden HTML elements.</p>
<p id="demo" style="display:none">Hello JavaScript!</p>
<button type="button"
onclick="document.getElementById('demo').style.display='block'">Click
Me!</button>
</body>
</html>
Output
38
Unit-II
FUNCTIONS AND LOOPS
Anatomy of a Function, Function Creation, Calling Function, Passing Arguments into
Functions, Conditionals, Loops, Programming Challenges for Functions and Loops
A function is a way to bundle code so that it can be reused.
Functions allow us to run the same piece of code from multiple places in a program without
having to copy and paste the code repeatedly.
Basic Anatomy of a Function
A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as
variables).
The parentheses may include parameter names separated by commas:(parameter1,
parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}
function name(parameter1, parameter2, parameter3)
{
// code to be executed
}
Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.
Example
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<p>Call a function which performs a calculation and returns the result:</p>
39
<p id="demo"></p>
<script>
Output
JavaScript Functions
Call a function which performs a calculation and returns the result:
12
Passing Arguments into Functions
A JavaScript function does not perform any checking on parameter values (arguments).
Function parameters are the names listed in the function definition.
Function arguments are the real values passed to (and received by) the function.
Parameter Rules
do not specify data types for parameters.
do not perform type checking on the passed arguments.
do not check the number of arguments received.
Syntax:
function functionName(parameter1, parameter2, parameter3) {
// code to be executed
}
Default Parameters
If a function is called with missing arguments (less than declared), the missing values are set
to undefined.
sometimes it is better to assign a default value to the parameter:
<!DOCTYPE html>
<html>
<body>
<p>Setting a default value to a function parameter.</p>
<p id="demo"></p>
<script>
function myFunction(x, y) {
if (y === undefined) {
41
y = 2;
}
return x * y;
}
document.getElementById("demo").innerHTML = myFunction(4);
</script>
</body>
</html>
Output
Setting default value to a function parameter.
8
Default Parameter Values
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<h2>Default Parameter Values</h2>
<p>If y is not passed or undefined, then y = 10:</p>
<p id="demo"></p>
<script>
function myFunction(x, y = 10) {
return x + y;
}
document.getElementById("demo").innerHTML = myFunction(5);
</script>
</body>
</html>
Output
JavaScript Functions
Default Parameter Values
If y is not passed or undefined, then y = 10:
15
42
Conditionals and loops
Conditionals and loops is called as control structures because they allow to control which
parts of code are executed when and how often they’re executed, based on certain conditions.
JavaScript have the following conditional statements:
o if - to specify a block of code to be executed, if a specified condition is true
o else to specify a block of code to be executed, if the same condition is false
o else if to specify a new condition to test, if the first condition is false
o switch to specify many alternative blocks of code to be executed
if Statement
f statement to specify a block of JavaScript code to be executed if a condition is true.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript if</h2>
<p>Display "Good day!" if the hour is less than 18:00:</p>
<p id="demo">Good Evening!</p>
<script>
if (new Date().getHours() < 18) {
document.getElementById("demo").innerHTML = "Good day!";
}
</script>
</body>
</html>
43
Output
JavaScript if
Display "Good day!" if the hour is less than 18:00:
Good day!
else Statement
else statement to specify a block of code to be executed if the condition is false.
Syntax
if (condition)
{
// block of code to be executed if the condition is true
}
else {
// block of code to be executed if the condition is false
}
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript if .. else</h2>
<p>A time-based greeting:</p>
<p id="demo"></p>
<script>
const hour = new Date().getHours();
let greeting;
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
document.getElementById("demo").innerHTML = greeting;
</script>
</body>
44
</html>
Output
JavaScript if .. else
A time-based greeting:
Good day
else if Statement
else if statement to specify a new condition if the first condition is false.
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
}
else if (condition2) {
// block of code to be executed if the condition1 is false and
condition2 is true
}
else {
// block of code to be executed if the condition1 is false and
condition2 is false
}
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript if .. else</h2>
<p>A time-based greeting:</p>
<p id="demo"></p>
<script>
const time = new Date().getHours();
let greeting;
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
45
greeting = "Good evening";
}
document.getElementById("demo").innerHTML = greeting;
</script>
</body>
</html>
Output
JavaScript if .. else
A time-based greeting:
Good day
Switch Statement
The switch statement is used to perform different actions based on different conditions.
Syntax
switch(expression) {
case x: // code block
break;
case y: // code block
break;
default: // code block
}
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript switch</h2>
<p id="demo"></p>
<script>
let day;
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
46
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
document.getElementById("demo").innerHTML = "Today is " + day;
</script>
</body>
</html>
Output
JavaScript switch
Today is Saturday
Different Kinds of Loops
for - loops through a block of code a number of times
while - loops through a block of code while a specified condition is true
do/while - also loops through a block of code while a specified condition is true
For Loop
The for statement creates a loop with 3 optional expressions:
for (expression 1; expression 2; expression 3) {
// code block to be executed
}
Expression 1 is executed (one time) before the execution of the code block.
Expression 2 defines the condition for executing the code block.
47
Expression 3 is executed (every time) after the code block has been executed.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For Loop</h2>
<p id="demo"></p>
<script>
let text = "";
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Output
JavaScript While Loop
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
do -while Loop
The do while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition is
true.
Syntax
do {
// code block to be executed
}
while (condition);
<!DOCTYPE html>
49
<html>
<body>
<h2>JavaScript Do While Loop</h2>
<p id="demo"></p>
<script>
let text = ""
let i = 0;
do {
text += "<br>The number is " + i;
i++;
}
while (i < 10);
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Output
JavaScript Do While Loop
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
50
UNIT 3
ADVANCED JAVASCRIPT
DOM and jQuery, Interactive Programming, Mouse Events, Buried Treasure - Creating the Web
Page with HTML, Picking a Random Treasure Location, Click Handler, Object Oriented
Programming - Adding Methods to Objects, Creating Objects Using Constructors, Customizing
Objects with Prototypes.
DOCUMENT OBJECT MODEL
DOM is a way to represent the webpage in a structured hierarchical way so that it will
become easier for programmers and users to glide through the document.
With DOM, we can easily access and manipulate tags, IDs, classes, Attributes, or Elements
of HTML using commands or methods provided by the Document object. Using DOM, the
JavaScript gets access to HTML as well as CSS of the web page and can also add behavior
to the HTML elements. so basically Document Object Model is an API that represents and
interacts with HTML or XML documents.
Why DOM is required?
HTML is used to structure the web pages and Javascript is used to add behavior to our
web pages. When an HTML file is loaded into the browser, the javascript can not
understand the HTML document directly. So it interprets and interacts with the Document
Object Model (DOM), which is created by the browser based on the HTML
document. DOM is basically the representation of the same HTML document but in a
tree-like structure composed of objects.
The Document Object Model (DOM) is essential in web development for several reasons:
Dynamic Web Pages: It allows you to create dynamic web pages. It enables the JavaScript to
access and manipulate page content, structure, and style dynamically which gives interactive and
51
responsive web experiences, such as updating content without reloading the entire page or
responding to user actions instantly.
Interactivity: With the DOM, you can respond to user actions (like clicks, inputs, or scrolls) and
modify the web page accordingly.
Content Updates: When you want to update the content without refreshing the entire page, the
DOM enables targeted changes making the web applications more efficient and user-friendly.
Cross-Browser Compatibility: Different browsers may render HTML and CSS in different ways.
The DOM provides a standardized way to interact with page elements.
Single-Page Applications (SPAs): Applications built with frameworks such as React or Angular,
heavily rely on the DOM for efficient rendering and updating of content within a single HTML
page without reloading the full page.
The HTML DOM (Document Object Model)
When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM model is constructed as a tree of Objects:
HTML DOM TRESS OF OBJECTS
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
JavaScript can change all the HTML elements in the page
JavaScript can change all the HTML attributes in the page
JavaScript can change all the CSS styles in the page
JavaScript can remove existing HTML elements and attributes
JavaScript can add new HTML elements and attributes
JavaScript can react to all existing HTML events in the page
52
JavaScript can create new HTML events in the page
What is the DOM?
he 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.
The W3C DOM standard is separated into 3 different parts:
Core DOM - standard model for all document types
XML DOM - standard model for XML documents
HTML DOM - standard model for HTML documents
53
<body>
<h2>My First Page</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
OUTPUT
My First Page
Hello World!
document.getElementById("demo").innerHTML =
"The text from the intro paragraph is: " + element.innerHTML;
</script>
</body>
</html>
OUTPUT
JavaScript HTML DOM
Finding HTML Elements by Id
Finding HTML Elements by Tag Name
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<p>Finding HTML Elements by Tag Name.</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method.</p>
<p id="demo"></p>
<script>
const element = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = 'The text in first paragraph (index 0) is: ' +
element[0].innerHTML;
</script>
</body>
</html>
OUTPUT
55
JavaScript HTML DOM
Finding HTML Elements by Tag Name.
OUTPUT
The following HTML objects (and object collections) are also accessible:
document.anchors
57
document.body
document.documentElement
document.embeds
document.forms
document.head
document.images
document.links
document.scripts
document.title
The HTML DOM allows JavaScript to change the content of HTML elements.
Changing HTML Content
The easiest way to modify the content of an HTML element is by using
the innerHTML property.
To change the content of an HTML element, use this syntax:
document.getElementById(id).innerHTML = new HTML
This example changes the content of a <p> element:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript can Change HTML</h2>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML = "New text!";
</script>
<p>The paragraph above was changed by a script.</p>
</body>
</html>
OUTPUT
JavaScript can Change HTML
New text!
The paragraph above was changed by a script.
JavaScript Form Validation
58
HTML form validation can be done by JavaScript.
If a form field (fname) is empty, this function alerts a message, and returns false, to prevent
the form from being submitted:
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>
<h2>JavaScript Validation</h2>
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()"
method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
OUTPUT
59
JavaScript Can Validate Numeric Input
JavaScript is often used to validate numeric input:
<!DOCTYPE html>
<html><body>
<h2>JavaScript Validation</h2>
60
jQuery
jQuery is a lightweight, "write less, do more", JavaScript library.
The purpose of jQuery is to make it much easier to use JavaScript on your website.
61
jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish,
and wraps them into methods that you can call with a single line of code.
jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and
DOM manipulation.
The jQuery library contains the following features:
HTML/DOM manipulation
CSS manipulation
HTML event methods
Effects and animations
AJAX
Utilities
Why jQuery?
jQuery is probably the most popular, and also the most extendable.
Many of the biggest companies on the Web use jQuery, such as:
Google
Microsoft
IBM
Netflix
Adding jQuery to Your Web Pages
There are several ways to start using jQuery on your web site. You can:
Download the jQuery library from jQuery.com
Include jQuery from a CDN, like Google
jQuery Syntax
jQuery Syntax
The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the
element(s).
Basic syntax is: $(selector).action()
A $ sign to define/access jQuery
A (selector) to "query (or find)" HTML elements
A jQuery action() to be performed on the element(s)
Examples:
$(this).hide() - hides the current element.
$("p").hide() - hides all <p> elements.
$(".test").hide() - hides all elements with class="test".
62
$("#test").hide() - hides the element with id="test".
The Document Ready Event
$(document).ready(function(){
// jQuery methods go here...
});
This is to prevent any jQuery code from running before the document is finished loading (is ready).
It is good practice to wait for the document to be fully loaded and ready before working with it. This
also allows you to have your JavaScript code before the body of your document, in the head section.
jQuery Selectors
jQuery selectors allow you to select and manipulate HTML element(s).
jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types,
attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in
addition, it has some own custom selectors.
All selectors in jQuery start with the dollar sign and parentheses: $().
The element Selector
The jQuery element selector selects elements based on the element name.
Example
When a user clicks on a button, all <p> elements will be hidden:
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
The #id Selector
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.
An id should be unique within a page, so you should use the #id selector when you want to find a
single, unique element.
To find an element with a specific id, write a hash character, followed by the id of the HTML
element:
$("#test")
The .class Selector
The jQuery .class selector finds elements with a specific class.
To find elements with a specific class, write a period character, followed by the name of the class:
63
$(".test")
JavaScript / jQuery HTML DOM
jQuery vs JavaScript
jQuery was created in 2006 by John Resig.
It was designed to handle Browser Incompatibilities and to simplify HTML DOM
Manipulation, Event Handling, Animations, and Ajax.
EXAMPLE
<!DOCTYPE html>
<html>
<body>
<h2>Finding HTML Elements by Id</h2>
<p id="id01">Hello World!</p>
<p id="id02">Hello Sweden!</p>
<p id="id03">Hello Japan!</p>
<p id="demo"></p>
<script>
const myElement = document.getElementById("id01");
document.getElementById("demo").innerHTML = "The text from the id01 paragraph
is: " + myElement.innerHTML;
</script>
</body>
</html>
OUTPUT
Finding HTML Elements by Id
Hello World!
Hello Sweden!
Hello Japan!
The text from the id01 paragraph is: Hello World!
Mouse Events
Mouse event is an event which gets generate when mouse interacts with html elements
which are register to mouse Event object.
65
There are different events related to mouse event like mouse click, mouse over, mouse
out etc. Whenever a mouse event is generated some activity or action is performed by
the browser.
The action performed to handle a mouse event is called mouse event handler and the
process to handle a mouse event is called mouse event handler.
66
document.getElementById("divid").innerHTML="The Mouse click event is generated and it
handled.";
}
</script>
<div id="divid" style="color: #0900C4"></div>
</body>
</html>
As in the above code the mouse click event is generated once when we click the button.
The button is register or specify the onclick handler function as well that is funHandler()
function, so when the button is clicked the click event get generate and funHandler() function
executes, which is printing some text as shown in above output.
Example1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mouse Movement</title>
<style>
#mouseMovementDemo {
width: 300px;
height: 200px;
background-color: lightblue;
border: 1px solid #000;
margin: 20px;
position: relative;
}
#mousePosition {
position: absolute;
bottom: 10px;
left: 10px;
67
}
</style>
</head>
<body>
<div id="mouseMovementDemo"></div>
<div id="mousePosition">Mouse Position: (0, 0)</div>
<script>
var mouseMovementDemo = document.getElementById("mouseMovementDemo");
var mousePositionDisplay = document.getElementById("mousePosition");
Output
68
Example2
mouseup event
<!DOCTYPE html>
<html lang= "en" >
<head>
<title> This is an example for mouse events </title>
</head>
<body>
<!-- code to show working of onmouseup handler -->
<button onmouseup= "funHandler()" style="color:#FF0000"> Click here to generate mouse
up event. </button>
<script>
function funHandler() {
document.getElementById("divid").innerHTML="The Mouse up event is generated and it
handled.";
}
</script>
69
<div id="divid" style="color: #0900C4"></div>
</body>
</html>
As in the above code the mouse up event is handle once when we press the button. The button
is register or specify the onmouseup handler function as well that is funHandler() function, so
when the button is pressed the onmouseup event get generate and funHandler() function is
executes, which is printing some text as shown in above output.
Example3
mousedown event
<!DOCTYPE html>
<head>
<title> This is an example for mouse events </title>
</head>
<body>
<!-- code to show working of onmousedown handler -->
<button onmousedown= "funHandler()" style="color:#FF0000"> Click here to generate
mouse down event. </button>
<script>
function funHandler() {
document.getElementById("divid").innerHTML="The Mouse down event is generated and it
handled.";
}
</script>
<div id="divid" style="color: #0900C4"></div>
</body>
</html>
As in the above code the mouse down event is handling once when we released (after
pressed) the button. The button specify the onmousedown handler function that is
funHandler() function, so when the button is released the onmousedown event gets generate
and funHandler() function is executed, which is printing some text as shown in above output.
Buried Treasure
The Treasure Hunt Game was created using JavaScript programming language. This is a
user-friendly kind of application that is free to be modified. The gameplay is simple you just
need to find the treasure hidden in the tile. The player can play the game using mouse, you
just only need to use the Left Mouse Button to dig and locate the treasure. Your main goal in
the game is to find and locate the treasure before your life runs out. You will be given a
70
limited amount of life enough to get your treasure. Each dig will deduct your lifebar and will
decrease continuously if the treasure is not found yet. There is a hint each time you dug, try to
follow the hint in order to get your treasure.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Buried Treasure Game</title>
<style>
#game-container {
display: grid;
grid-template-columns: repeat(5, 100px);
grid-gap: 5px;
}
cell {
width: 100px;
height: 100px;
border: 1px solid #000;
display: flex;
align-items: center;
justify-content: center;
font-size: 18px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="game-container"></div>
<script>
const gameContainer = document.getElementById("game-container");
const rows = 5;
71
const columns = 5;
const treasureCell = { row: Math.floor(Math.random() * rows), column:
Math.floor(Math.random() * columns) };
function createGameBoard() {
for (let i = 0; i < rows; i++) {
for (let j = 0; j < columns; j++) {
const cell = document.createElement("div");
cell.classList.add("cell");
cell.dataset.row = i;
cell.dataset.column = j;
cell.addEventListener("click", handleCellClick);
gameContainer.appendChild(cell);
}
}
}
function handleCellClick(event) {
const clickedCell = event.target;
const clickedRow = parseInt(clickedCell.dataset.row);
const clickedColumn = parseInt(clickedCell.dataset.column);
OUTPUT
72
Creating the WebPage with HTML
EXAMPLE
<!DOCTYPE html>
<html lang="en">
73
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Your Web Page Title</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
header {
text-align: center;
padding: 20px;
background-color: #f0f0f0;
}
main {
max-width: 800px;
margin: 0 auto;
}
footer {
text-align: center;
padding: 10px;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<header>
<h1>Your Website Name</h1>
<p>Welcome to your website!</p>
</header>
<main>
<section>
<h2>About Us</h2>
74
<p>This is a brief description of your website and what it offers.</p>
</section>
<section>
<h2>Contact Us</h2>
<p>You can reach us at your@email.com</p>
</section>
</main>
<footer>
© 2024 Your Website Name. All rights reserved.
</footer>
</body>
</html>
OUTPUT
Object-Oriented Programming
Object–Oriented Programming Concepts:
75
Objects
Classes
Inheritance
Abstraction
Encapsulation
Polymorphism
Overloading
Dynamic binding
Message passing
Objects:
Objects are the basic run-time entities.
They may represent a person, a place, a bank account or any item that the program has to
handle.
Each object contains data and code to manipulate the data.
Objects can interact without having to know the details of each other’s data or code.
76
Classes:
To combine data and the function in a single unit is called a class.
Once a class is defined, we a declare variables of that type.
A class variable is called object or instance.
Classes are generally declared using the keyword class, with the following format:
class class_name
{
private:
members1;
protected:
members2;
public:
members3; };
77
By default, all members of a class declared with the class keyword have private access for all
its members. Therefore, any member that is declared before one other class specifier
automatically has private access.
Encapsulation
Wrapping up data and information under a single unit.
For example, in a company, there are different sections like the accounts section, finance
section, sales section, etc. The finance section handles all the financial transactions and keeps
records of all the data related to finance.
Similarly, the sales section handles all the sales-related activities and keeps records of all the
sales.
Now there may arise a situation when for some reason an official from the finance section
needs all the data about sales in a particular month.
In this case, it is not allowed to directly access the data of the sales section.
First, have to contact some other officer in the sales section and then request him to give the
particular data. Here the data of the sales section and the employees that can manipulate them
are wrapped under a single name “sales section”.
Abstraction
Data abstraction refers to providing only essential information about the data to the outside
world, hiding the background details or implementation.
Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerator will increase the speed of the car or applying brakes will stop the car but he does
not know how on pressing the accelerator the speed is actually increasing, he does not know
about the inner mechanism of the car or the implementation of an accelerator, brakes, etc. in
the car.
Polymorphism
78
Polymorphism means many forms.
Ability of a message to be displayed in more than one form.
There are two types of polymorphism:
o Run-time polymorphism
o Compile-time polymorphism
Method Overloading
o Compile-time polymorphism-define various functions with the same name but
different numbers of arguments. The function call is resolved at compile time, so it's a
type of compile-time polymorphism. Here resolution of the function call implies
binding to the correct function definition depending on the arguments passed in the
function call.
Method Overriding
o Run-time polymorphism-It allows overriding a parent class’s method by a child class.
Overriding means that a child class provides a new implementation of the same
method it inherits from the parent class.
Example:
a parent class called “Shape” with a method named “findArea” that calculates and
returns the area of the shape.
Several sub-classes inherit from the “Shape,” like Square, Circle, Rectangle, etc. Each
of them will define the function “findArea” in its way, thus overriding the function.
Inheritance
The capability of a class to derive properties and characteristics from another class is called
Inheritance.
79
Sub Class: The class that inherits properties from another class is called Sub class or Derived
Class.
Super Class: The class whose properties are inherited by a sub-class is called Base Class or
Superclass.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a
new class and there is already a class that includes some of the code that we want, we can
derive our new class from the existing class. By doing this, we are reusing the fields and
methods of the existing class.
Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.
Dynamic Binding
Binding refers to the linking of a procedure call to the code to the executed in response to the
function call.
Dynamic binding means the code associated with a given procedure call is not known until
the time of the call at run-time.
Message Passing
Objects communicate with one another by sending and receiving information.
A message for an object is a request for the execution of a procedure and therefore will
invoke a function in the receiving object that generates the desired results.
80
Message passing involves specifying the name of the object, the name of the function, and the
information to be sent.
UNIT 4
CANVAS
HTML Canvas
The HTML <canvas> element is used to draw graphical data presentation with an imagery of
graphs and charts.
Canvas has several methods for drawing paths, boxes, circles, text, and adding images.
It can draw colorful text, with or without animation.
Canvas can respond to JavaScript events and respond to any user action (key clicks, mouse
clicks, button clicks, finger movement).
Example
<canvas id="myCanvas" width="200" height="100"></canvas>
<canvas> element must have an id attribute .
It can be referred to by JavaScript.
width and height attribute is to define the size of the canvas.
<!DOCTYPE html>
<html>
81
<body>
<h1>HTML5 Canvas</h1>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;"></canvas>
</body>
</html>
Output
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px dashed orangered;">
Your browser does not support the HTML canvas tag.
</canvas>
</body>
</html>
Output:
82
Drawing on the Canvas
Selecting and Saving the canvas Element
select the canvas element using document.getElementById("canvas").
This method returns a DOM object representing the element with the supplied id.
This object is assigned to the canvas variable with the code
var canvas = document.getElementById("canvas").
Getting the Drawing Context
A drawing context is a JavaScript object that includes all the methods and properties for
drawing on a canvas.
getContext on canvas and pass it the string "2d" as an argument.
This argument to draw a two-dimensional image on our canvas.
save this drawing context object in the variable ctx .
var ctx = canvas.getContext("2d").
Output
83
Drawing Rectangle Outlines
To draw outline of a rectangle, we use the strokeRect method.
The word stroke is another word for outline.
strokeRect method takes the same arguments as fillRect,first the x- and y-coordinates of the
top-left corner, followed by the width and height of the rectangle.
<!DOCTYPE html>
<html>
<body>
<h1>HTML5 Canvas</h1>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid grey;"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.strokeRect(10, 10, 100, 20);
</script>
</body>
</html>
Output
84
strokeStyle property to change the color of the rectangle’s outline.
To change the thickness of the line, use the lineWidth property.
For example:
<!DOCTYPE html>
<html>
<body>
<h1>HTML5 Canvas</h1>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid grey;"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.strokeStyle = "DeepPink";
ctx.lineWidth = 4;
ctx.strokeRect(10, 10, 100, 20)
</script>
</body>
</html>
Drawing Lines or Paths
Lines on the canvas are called paths.
To draw a path with the canvas, use x- and y-coordinates to set where each line should begin
and end. By using a careful combination of starting and stopping coordinates, draw specific
shapes on the canvas.
To draw a straight line on a canvas, use the following methods:
o beginPath() - begins a path
o moveTo(x,y) - defines the starting point of the line
85
o lineTo(x,y) - defines the ending point of the line
Draw a rectangle with a starting point in position (0,0), and an ending point in position
(200,100).
Using a stroke() method to draw the line.
<!DOCTYPE html>
<html>
<body>
<h1>HTML5 Canvas</h1>
<h2>Draw a Line</h2>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid grey;"></canvas>
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
</script>
</body>
</html>
Output
Example
<!DOCTYPE html>
<html lang="en">
<head>
86
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas Line, Path, and Circle</title>
</head>
<body>
<canvas id="myCanvas" width="400" height="300" style="border:1px solid grey;"></canvas>
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.strokeStyle = "#00FF00"; // Green
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(150, 50);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(50, 100);
ctx.lineTo(150, 150);
ctx.stroke();
ctx.beginPath();
ctx.rect(200, 50, 100, 75);
ctx.beginPath();
ctx.arc(300, 200, 50, 0, 2 * Math.PI);
ctx.stroke();
</script>
</body>
</html>
Output :
87
Draw a Circle
To draw a circle on a canvas, use arc () methods.
arc(x,y,r,startangle,endangle) - creates an arc/curve.
Set start angle to 0 and end angle to 2*Math.PI.
x- and y-coordinates of the center of the circle.
r parameter -radius of the circle.
<!DOCTYPE html>
<html>
<body>
<h1>HTML5 Canvas</h1>
<h2>The arc() Method</h2>
<canvas id="myCanvas" width="200" height="120" style="border:1px solid #d3d3d3;"></canvas>
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(100,50,50,0,2*Math.PI);
88
ctx.stroke();
</script>
</body>
</html>
Output
Methods
beginPath() method starts a new path.It does not draw anything, it just defines a new path.
89
moveTo() defines the starting point of the line.It does not draw anything, it just sets a start
point.
lineTo() method defines the end point of the line.It does not draw anything, just sets an end
point.
stroke() method draws to line. The default stroke color is black.
Drawing Lots of Circles with Function
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Draw Circles with Canvas</title>
<style>
body {
margin: 0;
overflow: hidden;
}
</style>
</head>
<body>
<canvas id="myCanvas"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
function drawCircle(x, y, radius) {
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.fillStyle = "blue"; // Set the circle color
90
ctx.fill();
ctx.closePath();
}
function drawRandomCircles(numCircles) {
for (var i = 0; i < numCircles; i++) {
var x = Math.random() * canvas.width;
var y = Math.random() * canvas.height;
var radius = Math.random() * 50 + 10;
drawCircle(x, y, radius);
}
}
drawRandomCircles(100);
</script>
</body>
</html>
Output
Bouncing a Ball
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bouncing Ball Animation</title>
<style>
canvas {
border: 1px solid #000;
}
92
</style>
</head>
<body>
<canvas id="bouncingBallCanvas" width="400" height="300"></canvas>
<script>
var canvas = document.getElementById("bouncingBallCanvas");
var ctx = canvas.getContext("2d");
var ball = {
x: 50,
y: 50,
radius: 20,
color: "blue",
speedX: 5,
speedY: 2
};
function drawBall() {
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, 2 * Math.PI);
ctx.fillStyle = ball.color;
ctx.fill();
ctx.closePath();
}
function updateBall() {
ball.x += ball.speedX;
ball.y += ball.speedY;
if (ball.x - ball.radius < 0 || ball.x + ball.radius > canvas.width) {
ball.speedX = -ball.speedX;
}
if (ball.y - ball.radius < 0 || ball.y + ball.radius > canvas.height) {
ball.speedY = -ball.speedY;
}
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
93
drawBall();
updateBall();
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
Output
KeyboardEvent
JavaScript can monitor the keyboard through keyboard events.
Each time a user presses a key on the keyboard, they generate a keyboard event.
mouse events, we used jQuery to determine where the cursor was when the event took place.
keyboard events, use jQuery to determine which key was pressed and then use information.
a ball moves left, right, up, or down when the user presses the left, right, up, or down arrow
key.
keydown event, which is triggered whenever a user presses a key.
KeyboardEvent Object
KeyboardEvent Object handles events that occur when a user presses a key on the keyboard.
94
Event Occurs When
1. onkeydown A user presses a key
2. onkeypress A user presses a key
3. onkeyup A user releases a key
KeyboardEvent Methods
getModifierState()- Returns true if the specified key is activated
Moving a Ball with the Keyboard.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script>
var myGamePiece;
function startGame() {
myGamePiece = new component(30, 30, "red", 225, 225);
myGameArea.start(); }
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function (e) {
95
e.preventDefault();
myGameArea.keys = (myGameArea.keys || []);
myGameArea.keys[e.keyCode] = (e.type == "keydown");
})
window.addEventListener('keyup', function (e) {
myGameArea.keys[e.keyCode] = (e.type == "keydown");
})
},
stop : function() {
clearInterval(this.interval);
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y, type) {
this.type = type;
this.width = width;
this.height = height;
this.speed = 0;
this.angle = 0;
this.moveAngle = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.fillStyle = color;
ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);
ctx.restore();
}
96
this.newPos = function() {
this.angle += this.moveAngle * Math.PI / 180;
this.x += this.speed * Math.sin(this.angle);
this.y -= this.speed * Math.cos(this.angle);
}
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.moveAngle = 0;
myGamePiece.speed = 0;
if (myGameArea.keys && myGameArea.keys[37]) {myGamePiece.moveAngle = -1; }
if (myGameArea.keys && myGameArea.keys[39]) {myGamePiece.moveAngle = 1; }
if (myGameArea.keys && myGameArea.keys[38]) {myGamePiece.speed= 1; }
if (myGameArea.keys && myGameArea.keys[40]) {myGamePiece.speed= -1; }
myGamePiece.newPos();
myGamePiece.update();
}
</script>
<p>Make sure the gamearea has focus, and use the arrow keys to move the red square
around.</p>
</body>
</html>
Output:
97
UNIT 5
GAME DEVELOPMENT
In the function that we pass to setInterval, the first line clears the canvas with clearRect so that we
can draw the next step in the animation.
Structure of the Game and Game Setup
98
Set up the canvas
Set score to zero
Create snake
Create apple
Every 100 milliseconds {
Clear the canvas
Draw current score on the screen
Move snake in current direction
If snake collides with wall or itself {
End the game
} Else If snake eats an apple {
Add one to score
Move apple to new location
Make snake longer
}
For each segment of the snake {
Draw the segment
}
Draw apple
Draw border
}
When the user presses a key {
If the key is an arrow {
Update the direction of the snake
}
}
99
Creating a Snake game in JavaScript involves combining HTML5 Canvas for rendering,
keyboard events for user input, and game logic to manage the state of the snake, the food, and handle
collisions. Here's a high-level explanation of the key components and concepts involved:
1. HTML5 Canvas:
The game's graphics are drawn on an HTML5 Canvas element. The canvas provides a 2D
drawing context that allows you to draw shapes, text, and images.
HTML Syntax :<canvas id="board"></canvas>
Explanation: This creates an HTML5 canvas element with the id "board" where the game
graphics will be drawn.
100
4.User Input - Keyboard Events:
Listen for keyboard events to change the direction of the snake. You can use the
document.addEventListener method to capture arrow key presses.
Javascript syntax:
document.addEventListener("keyup", changeDirection);
This adds an event listener to the document that listens for keyup events. When a key is released, the
changeDirection function is called.
function changeDirection(e) {
if (e.code === "ArrowUp" && speedY !== 1) {
speedX = 0;
speedY = -1;
} else if (e.code === "ArrowDown" && speedY !== -1) {
speedX = 0;
speedY = 1;
} else if (e.code === "ArrowLeft" && speedX !== 1) {
speedX = -1;
speedY = 0;
} else if (e.code === "ArrowRight" && speedX !== -1) {
speedX = 1;
speedY = 0;
}
}
This function (changeDirection) is called when a key is released. It adjusts the snake's speed
based on the arrow key pressed, making sure the snake can't move in the opposite direction.
5.Game Loop:
The game loop, often implemented using setInterval or requestAnimationFrame, updates
the game state and redraws the canvas at regular intervals.
Javascript syntax
setInterval(update, 1000 / 10);
The update function is the core of the game logic. It's where you update the game state (move the
snake, check for collisions, etc.) and redraw the canvas.
101
function update() {
// Update game state
// Draw on the canvas
}
The update function is the core of the game logic. It's where you update the game state (move the
snake, check for collisions, etc.) and redraw the canvas.
6.Collision Detection:
Check for collisions between the snake and the food, the snake and the canvas boundaries,
and the snake and itself.
Javascript syntax:
if (snakeX === foodX && snakeY === foodY) {
// Handle food collision
}
if (snakeX < 0 || snakeX >= canvasWidth || snakeY < 0 || snakeY >= canvasHeight) {
// Handle boundary collision
gameOver = true;
}
for (let i = 1; i < snakeBody.length; i++) {
if (snakeX === snakeBody[i].x && snakeY === snakeBody[i].y) {
// Handle self-collision
gameOver = true;
}
}
These conditions check for different types of collisions:
If the snake's head reaches the food, handle a food collision.
If the snake's head goes out of bounds, set the gameOver flag to true.
Check for self-collision by comparing the head's position with each segment of the snake's
body.
These explanations cover the fundamental aspects of the Snake game code, providing an overview
of how the game state is managed, how user input is handled, and how collisions are detected.
102
Drawing the Border
we’ll create a drawBorder function to draw a border around the canvas. We’ll make this border one
block (10 pixels) thick Our function will draw four long, thin rectangles, one for each edge of the
border. Each rectangle will be blockSize (10 pixels) thick and the full width or height of the canvas
var drawBorder = function () {
ctx.fillStyle = "Gray";
u ctx.fillRect(0, 0, width, blockSize);
v ctx.fillRect(0, height - blockSize, width, blockSize);
w ctx.fillRect(0, 0, blockSize, height);
x ctx.fillRect(width - blockSize, 0, blockSize, height);
};
1. HTML Structure:
The HTML structure includes a canvas element with the id "board" and a specified width and
height, styled with CSS to have a 2-pixel solid black border and light gray background.
2. Styling with CSS:
The CSS styling sets the canvas border to 2 pixels solid black, centers it on the page with a
margin, and provides a light gray background, creating a visually appealing canvas display.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas Border</title>
<style>
#board {
border: 2px solid black;
display: block;
margin: 20px auto;
background-color: lightgray;
}
</style>
</head>
<body>
103
<canvas id="board" width="400" height="300"></canvas>
<script>
// You can add your own JavaScript code here if needed
</script>
</body>
</html>
OUTPUT
CSS Styling:
104
The CSS styles define the appearance of the canvas, including a 2-pixel solid black border,
centered display, and a light gray background.
The score is styled to be centered with a font size of 20 pixels.
JavaScript: Initialization and Constants:
The code starts with initializing variables for the canvas, snake, speed, food, score, and game
state.
Constants like blockSize, numRows, and numCols define the size and layout of the game.
Window Onload Function:
The window.onload function sets up the initial state of the game when the page loads.
It initializes the canvas and sets up event listeners for keyboard input.
Drawing Functions:
The update function is the game loop responsible for updating and rendering the game state.
It clears the canvas, draws the border, food, and snake on the canvas.
The snake's body is drawn based on its current segments.
Collision detection checks for boundaries, self-collision, and food collision.
Score Handling:
The score variable keeps track of the player's score, which is displayed on the page.
The updateScore function updates the displayed score whenever the snake eats food.
The score is incremented by 10 each time the snake consumes food.
User Input - Keyboard Events:
The changeDirection function handles user input by updating the snake's speed based
on arrow key presses.
It prevents the snake from moving in the opposite direction.
Food Placement:
The placeFood function randomly places food on the canvas when called.
Game Over Handling:
When a game over condition is met (boundary collision or self-collision), an alert is displayed
with the final score.
Set Timeout for Animation:
The setTimeout function is used to create a loop that repeatedly calls the update function,
creating an animation effect.
EXAMPLE
<!DOCTYPE html>
105
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snake Game</title>
<style>
#board {
border: 2px solid black;
display: block;
margin: 20px auto;
background-color: lightgray;
}
#score {
text-align: center;
font-size: 20px;
}
</style>
</head>
<body>
<h2 id="score">Score: 0</h2>
<canvas id="board" width="400" height="300"></canvas>
<script>
(function () {
let blockSize = 25;
let numRows = 17;
let numCols = 17;
let board;
let context;
let snakeX = blockSize * 5;
let snakeY = blockSize * 5;
let speedX = 0;
let speedY = 0;
context.fillStyle = "yellow";
context.fillRect(foodX, foodY, blockSize, blockSize);
context.fillStyle = "white";
context.fillRect(snakeX, snakeY, blockSize, blockSize);
snakeBody.forEach(segment => {
context.fillRect(segment.x, segment.y, blockSize, blockSize);
});
for (let i = snakeBody.length - 1; i > 0; i--) {
snakeBody[i] = Object.assign({}, snakeBody[i - 1]);
}
if (snakeBody.length) {
107
snakeBody[0] = { x: snakeX, y: snakeY };
}
snakeX += speedX * blockSize;
snakeY += speedY * blockSize;
if (snakeX < 0 || snakeX >= numCols * blockSize || snakeY < 0 || snakeY >= numRows *
blockSize) {
gameOver = true;
alert("Game Over. Your Score: " + score);
}
for (let i = 1; i < snakeBody.length; i++) {
if (snakeX === snakeBody[i].x && snakeY === snakeBody[i].y) {
gameOver = true;
alert("Game Over. Your Score: " + score);
}
}
if (snakeX === foodX && snakeY === foodY) {
snakeBody.push({ x: foodX, y: foodY });
placeFood();
score += 10;
updateScore();
}
setTimeout(update, 150);
}
function changeDirection(e) {
if (e.code === "ArrowUp" && speedY !== 1) {
speedX = 0;
speedY = -1;
} else if (e.code === "ArrowDown" && speedY !== -1) {
speedX = 0;
speedY = 1;
}
OUTPUT
109
Ending the Game
gameOver function to end the game when the snake hits the wall or runs into itself.
The gameOver function uses clearIntervalto stop the game and writes the text “Game Over”
on the canvas.
var gameOver = function () {
clearInterval(intervalId);
ctx.font = "60px Courier";
ctx.fillStyle = "Black";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("Game Over", width / 2, height / 2);
};
game by calling clearInterval and passing in the variable intervalId.
This cancels the setInterval animation function that we created in “Using setInterval to
Animate the GameNext, we set our font to 60-pixel Courier in black, center the text, and set
the textBaseline property to "middle".
call fillText and tell it to draw the string "Game Over" with width / 2 for the x-position and
height / 2 for the y-position.
The resulting “Game Over” text will be centered in the canvas.
110