0% found this document useful (0 votes)
36 views140 pages

Full Stack Development-1

The document is a lab manual for a Full Stack Development course at Vijaya Institute of Technology for Women for the academic year 2024-25. It outlines the college's vision and mission, the department's objectives, and provides a comprehensive list of experiments and exercises focused on HTML, CSS, and JavaScript. The manual aims to equip students with practical skills in web development through various programming tasks and projects.

Uploaded by

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

Full Stack Development-1

The document is a lab manual for a Full Stack Development course at Vijaya Institute of Technology for Women for the academic year 2024-25. It outlines the college's vision and mission, the department's objectives, and provides a comprehensive list of experiments and exercises focused on HTML, CSS, and JavaScript. The manual aims to equip students with practical skills in web development through various programming tasks and projects.

Uploaded by

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

Department of Computer Science & Engineering

LAB MANUAL
FULL STACK DEVELOPMENT – 1

A.Y: 2024-25
Year/Semeter: II/II

Prepared by
K.Raju.

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


An ISO 9001:2015 Certified Institute, Approved by AICTE, Affiliated to JNTU
Kakinada, AP
Phone: 0866-2844444, Email:[email protected] Website: www.vitw.edu.in
COLLEGE VISION

Vijaya Institute of Technology for Women aims at empowering women engineers


with values and ethos to sustain across the globe and refining them as best
intellectuals to fit in the Competitive Society.

COLLEGE MISSION

1. To educate all students to the highest levels of academic achievement.


2. To enable the students to their potential and prepare them to become productive,
responsible, Creative members of the Society.
3. To enable students to gain Knowledge in ground breaking technologies.

DEPARTMENT VISION

Our vision is to cultivate a generation of highly skilled professionals in the fields


of Artificial Computer Science and Engineering Learning through the delivery of
exceptional education and training. We aim to attain international recognition as a
distinguished destination for excellence in CSE education and research.
DEPARTMENT MISSION

1. Rigorous Training and Knowledge Generation: Our foremost mission is to


provide
rigorous training to our students, enabling them to not only grasp but also generate
knowledge at the forefront of Artificial Intelligence and Machine Learning.
2. Cultivating Technical Proficiency and Leadership: We aim to develop technical
proficiency in our students by fostering creativity, critical thinking, and leadership
skills.
3. Promoting Lifelong Learning and Responsibility: We instill a culture of lifelong
learning in our students, emphasizing the importance of continuous self-
improvement and adaptation to evolving technological landscapes.
4. Establishing Centres of Excellence: We are committed to establishing and
maintaining centres of excellence in various areas of computer science and
artificial
intelligence disciplines.
Course Objectives:
The main objectives of the course are to
 Make use of HTML elements and their attributes for designing static web
pages
 Build a web page by applying appropriate CSS styles to HTML elements
 Experiment with JavaScript to develop dynamic web pages and validate
forms
LIST OF EXPERIMENTS
1. Lists, Links and Images
a. Write a HTML program, to explain the working of lists.
Note: It should have an ordered list, unordered list, nested lists and ordered list in an
unordered list and definition lists.
b. Write a HTML program, to explain the working of hyperlinks using <a> tag and href,
target Attributes.
c. Create a HTML document that has your image and your friend’s image with a specific
height and width. Also when clicked on the images it should navigate to their respective
profiles.
d. Write a HTML program, in such a way that, rather than placing large images on a page,
the preferred technique is to use thumbnails by setting the height and width parameters to
something like to 100*100 pixels. Each thumbnail image is also a link to a full sized
version of the image. Create an image gallery using this technique

2. HTML Tables, Forms and Frames


a. Write a HTML program, to explain the working of tables. (use tags: <table>, <tr>, <th>,
<td> and attributes: border, rowspan, colspan)
b. Write a HTML program, to explain the working of tables by preparing a
timetable. (Note: Use <caption> tag to set the caption to the table & also use cell spacing,
cell padding, border, rowspan, colspan etc.).
c. Write a HTML program, to explain the working of forms by designing Registration form.
(Note: Include text field, password field, number field, date of birth field, checkboxes,
radio buttons, list boxes using <select>&<option> tags, <text area> and two buttons ie:
submit and reset. Use tables to provide a better view).
d. Write a HTML program, to explain the working of frames, such that page is to be divided
into 3 parts on either direction. (Note: first frame  image, second frame  paragraph,
third frame  hyperlink. And also make sure of using “no frame” attribute such that
frames to be fixed).

3. HTML 5 and Cascading Style Sheets, Types of CSS


a. Write a HTML program, that makes use of <article>, <aside>, <figure>, <figcaption>,
<footer>, <header>, <main>, <nav>, <section>, <div>, <span> tags.
b. Write a HTML program, to embed audio and video into HTML web page.
c. Write a program to apply different types (or levels of styles or style specification formats)
- inline, internal, external styles to HTML elements. (identify selector, property and
value).
4. Selector forms
a. Write a program to apply different types of selector forms
i. Simple selector (element, id, class, group, universal)
ii. Combinator selector (descendant, child, adjacent sibling, general sibling)
iii. Pseudo-class selector
iv. Pseudo-element selector
v. Attribute selector

5. CSS with Color, Background, Font, Text and CSS Box Model
a. Write a program to demonstrate the various ways you can reference a color in CSS.
b. Write a CSS rule that places a background image halfway down the page, tilting it
horizontally. The image should remain in place when the user scrolls up or down.
c. Write a program using the following terms related to CSS font and text:
i. font-size ii. font-weight iii. font-style
iv. text-decoration v. text-transformation vi. text-alignment
d. Write a program, to explain the importance of CSS Box model using
i. Content ii. Border iii. Margin iv. Padding

6. Applying JavaScript - internal and external, I/O, Type Conversion


a. Write a program to embed internal and external JavaScript in a web page.
b. Write a program to explain the different ways for displaying output.
c. Write a program to explain the different ways for taking input.
d. Create a webpage which uses prompt dialogue box to ask a voter for his name
and age. Display the information in table format along with either the voter can vote or not.

7. Java Script Pre-defined and User-defined Objects


a. Write a program using document object properties and methods.
b. Write a program using window object properties and methods.
c. Write a program using array object properties and methods.
d. Write a program using math object properties and methods.
e. Write a program using string object properties and methods.
f. Write a program using regex object properties and methods.
g. Write a program using date object properties and methods.
h. Write a program to explain user-defined object by using properties, methods, accessors,
constructors and display.
8. Java Script Conditional Statements and Loops
a. Write a program which asks the user to enter three integers, obtains the numbers from the
user and outputs HTML text that displays the larger number followed by the words
“LARGER NUMBER” in an information message dialog. If the numbers are equal, output
HTML text as “EQUAL NUMBERS”.
b. Write a program to display week days using switch case.
c. Write a program to print 1 to 10 numbers using for, while and do-while loops.
d. Write aprogram to print data in object using for-in, for-each and for-of loops
e. Develop a program to determine whether a given number is an ‘ARMSTRONG
NUMBER’ or not. [Eg: 153 is an Armstrong number, since sum of the cube of the digits is
equal to the number i.e.,13 + 53+ 33 = 153]
f. Write a program to display the denomination of the amount deposited in the bank in terms
of 100’s, 50’s, 20’s, 10’s, 5’s, 2’s & 1’s. (Eg: If deposited amount is Rs.163, the output
should be 1-100’s, 1-50’s, 1- 10’s, 1-2’s & 1-1’s)

9. Java Script Functions and Events


a. Design a appropriate function should be called to display
i. Factorial of that number
ii. Fibonacci series up to that number
iii. Prime numbers up to that number
iv. Is it palindrome or not
b. Design a HTML having a text box and four buttons named Factorial, Fibonacci, Prime,
and Palindrome. When a button is pressed an appropriate function should be called to
display
i. Factorial of that number
ii. Fibonacci series up to that number
iii. Prime numbers up to that number
iv. Is it palindrome or not
c. Write a program to validate the following fields in a registration page
i.Name (start with alphabet and followed by alphanumeric and the length should
not be less than 6 characters)
ii. Mobile (only numbers and length 10 digits)
iii. E-mail (should contain format like [email protected])
EXERCISE:1
P1) Write a HTML program, to explain the working of lists.
Note: It should have an ordered list, unordered list, nested lists and ordered
list in an
unordered list and definition lists.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Lists Example</title>
</head>
<body>
<h1>HTML Lists</h1>
<h2>1. Ordered List (Numbered)</h2>
<p>An ordered list is a list where the items are numbered sequentially.</p>
<ol>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ol>
<h2>2. Unordered List (Bulleted)</h2>
<p>An unordered list is a list where the items are marked with bullet points.</p>
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Cherry</li>
</ul>
<h2>3. Nested Lists</h2>
<p>A nested list is a list within another list. It can be either ordered or unordered.</p>

<ul>
<li>Fruits
<ul>
<li>Apple</li>
<li>Orange</li>
<li>Grapes</li>
</ul>
</li>
<li>Vegetables
<ul>
<li>Carrot</li>
<li>Broccoli</li>
<li>Spinach</li>
</ul>
</li>
</ul>

<h2>4. Ordered List Inside Unordered List</h2>


<p>An ordered list placed inside an unordered list.</p>
<ul>
<li>First Category
<ol>
<li>Subitem 1</li>
<li>Subitem 2</li>
<li>Subitem 3</li>
</ol>
</li>
<li>Second Category
<ol>
<li>Subitem A</li>
<li>Subitem B</li>
</ol>
</li>
</ul>

<h2>5. Definition List</h2>


<p>A definition list is used for terms and their corresponding definitions.</p>
<dl>
<dt>HTML</dt>
<dd>HyperText Markup Language, the standard language for creating web pages.</dd>

<dt>CSS</dt>
<dd>Cascading Style Sheets, used to style and layout web pages.</dd>

<dt>JavaScript</dt>
<dd>A programming language used to make web pages interactive.</dd>
</dl>
</body>
</html>
P2) Write a HTML program, to explain the working of hyperlinks using <a>
tag and href, target Attributes.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Hyperlinks Example</title>
</head>
<body>

<h1>HTML Hyperlinks with &lt;a&gt; Tag</h1>

<h2>1. Basic Hyperlink using &lt;a&gt; tag and href attribute</h2>


<p>The <code>&lt;a&gt;</code> tag is used to create a hyperlink. The <code>href</code>
attribute specifies the destination of the link.</p>
<p>Click the link below to visit <strong>Google</strong>:</p>
<a href="https://www.google.com">Go to Google</a>

<h2>2. Hyperlink with target="_blank"</h2>


<p>The <code>target="_blank"</code> attribute makes the link open in a new browser tab or
window.</p>
<p>Click the link below to visit <strong>Wikipedia</strong> in a new tab:</p>
<a href="https://www.wikipedia.org" target="_blank">Go to Wikipedia (New Tab)</a>
<h2>3. Hyperlink to an Email Address</h2>
<p>You can also create a link that opens the user's email client with a predefined email
address. This uses the <code>mailto:</code> protocol.</p>
<p>Click the link below to send an email to the author:</p>
<a href="mailto:[email protected]">Email the Author</a>

<h2>4. Hyperlink to a Specific Section of the Same Page (Anchor Link)</h2>


<p>You can create links that navigate to a specific part of the same page using an anchor link.
The <code>href</code> points to an <code>id</code> attribute on the destination element.</p>
<p>Click the link below to jump to the "Anchor Section" on the same page:</p>
<a href="#anchor-section">Go to Anchor Section</a>

<h2 id="anchor-section">5. Anchor Section</h2>


<p>This is the section you jump to when you click the anchor link above. You can use this to
create a Table of Contents or navigation within a page.</p>

<h2>6. Hyperlink with Relative URL</h2>


<p>Links can also use relative URLs to link to other pages or files within the same website.
For example, this link assumes there's another HTML file called <code>about.html</code> in
the same directory:</p>
<a href="about.html">Go to About Page</a>

</body>
</html>
3) Create a HTML document that has your image and your friend’s image
with a specific height and width. Also when clicked on the images it should
navigate to their respective profiles.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Profile Images with Links</title>

</head>
<body>

<h1>Click on the Images to Visit Profiles</h1>

<!-- Your Image with a link to your profile -->


<a href="https://www.example.com/your-profile" target="_blank">
<img src="your-image.jpg" alt="Your Profile" class="profile-image" height="200"
width="200">
</a>
<p>Your Profile</p>
<!-- Friend's Image with a link to their profile -->
<a href="https://www.example.com/friends-profile" target="_blank">
<img src="friends-image.jpg" alt="Friend's Profile" class="profile-image" height="200"
width="200">
</a>
<p>Friend's Profile</p>

</body>
</html>
4) Write a HTML program, in such a way that, rather than placing large
images on a page, the preferred technique is to use thumbnails by setting the
height and width parameters to something like to 100*100 pixels. Each
thumbnail image is also a link to a full sized version of the image. Create an
image gallery using this technique.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Gallery</title>
<style>
.thumbnail img {
width: 100px;
height: 100px;
object-fit: cover;
}
</style>
</head>
<body>

<h1>Image Gallery</h1>

<div class="gallery">
<!-- Thumbnail 1 -->
<a href="fullsize-image1.jpg" target="_blank" class="thumbnail">
<img src="thumbnail-image1.jpg" alt="Image 1">
</a>

<!-- Thumbnail 2 -->


<a href="fullsize-image2.jpg" target="_blank" class="thumbnail">
<img src="thumbnail-image2.jpg" alt="Image 2">
</a>

<!-- Thumbnail 3 -->


<a href="fullsize-image3.jpg" target="_blank" class="thumbnail">
<img src="thumbnail-image3.jpg" alt="Image 3">
</a>

<!-- Thumbnail 4 -->


<a href="fullsize-image4.jpg" target="_blank" class="thumbnail">
<img src="thumbnail-image4.jpg" alt="Image 4">
</a>

<!-- Thumbnail 5 -->


<a href="fullsize-image5.jpg" target="_blank" class="thumbnail">
<img src="thumbnail-image5.jpg" alt="Image 5">
</a>

<!-- Thumbnail 6 -->


<a href="fullsize-image6.jpg" target="_blank" class="thumbnail">
<img src="thumbnail-image6.jpg" alt="Image 6">
</a>
</div>

</body>
</html>
EXERCISE:2

1) Write a HTML program, to explain the working of tables. (use tags:


<table>, <tr>, <th>, <td> and attributes: border, rowspan, colspan).

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Table Example</title>
</head>
<body>
<h1>Working with Tables in HTML</h1>

<h2>1. Simple Table</h2>


<p>This is a simple table that contains basic rows and columns.</p>
<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>

<tr>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
</tr>
<tr>
<td>Data 4</td>
<td>Data 5</td>
<td>Data 6</td>
</tr>
</table>

<h2>2. Table with Rowspan and Colspan</h2>


<p>This table uses the <code>rowspan</code> and <code>colspan</code>
attributes to span cells across multiple rows and columns.</p>
<table border="1">
<tr>
<th rowspan="2">Rowspan Example</th>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Data A</td>

<td>Data B</td>
</tr>
<tr>
<th colspan="2">Colspan Example</th>
<td>Data C</td>
</tr>
</table>

<h2>3. Another Example with Rowspan and Colspan</h2>


<p>This is another example to demonstrate how <code>rowspan</code> and
<code>colspan</code> work together in a more complex table layout.</p>
<table border="1">
<tr>
<th rowspan="2">A</th>
<th colspan="2">B</th>
<th rowspan="2">C</th>
</tr>
<tr>
<td>B1</td>
<td>B2</td>
</tr>
<tr>
<td>Data 1</td>
<td>Data 2</td>

<td>Data 3</td>
<td>Data 4</td>
</tr>
</table>

</body>
</html>
2) Write a HTML program, to explain the working of tables by preparing a
timetable. (Note: Use <caption> tag to set the caption to the table & also use
cell spacing, cell padding, border, rowspan, colspan etc.).

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weekly Timetable</title>
<!-- <style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
table {
width: 80%;
margin: 20px auto;
border: 2px solid #333;
border-collapse: collapse;
}
caption {
font-size: 24px;
font-weight: bold;
margin: 10px;
}
th, td {
border: 1px solid #333;
padding: 10px;
text-align: center;
font-size: 18px;
}
th {
background-color: #f2f2f2;
}
td {
background-color: #fafafa;
}
</style> -->
</head>
<body>

<h1>Student Timetable</h1>

<table cellspacing="10" cellpadding="15">


<caption>Weekly Timetable</caption>

<!-- Table Header -->


<tr>
<th rowspan="2">Time</th>
<th colspan="2">Monday</th>
<th colspan="2">Tuesday</th>
<th colspan="2">Wednesday</th>
<th colspan="2">Thursday</th>
<th colspan="2">Friday</th>
</tr>

<!-- Days of the week -->


<tr>
<th>Subject 1</th>
<th>Subject 2</th>
<th>Subject 1</th>
<th>Subject 2</th>
<th>Subject 1</th>
<th>Subject 2</th>
<th>Subject 1</th>
<th>Subject 2</th>
<th>Subject 1</th>
<th>Subject 2</th>
</tr>

<!-- Timetable rows -->


<tr>
<td>08:00 - 09:00</td>
<td>Math</td>
<td>English</td>
<td>Science</td>
<td>History</td>
<td>Geography</td>
<td>Art</td>
<td>Physics</td>
<td>Chemistry</td>
<td>Biology</td>
<td>PE</td>
</tr>
<tr>
<td>09:00 - 10:00</td>
<td>English</td>
<td>Math</td>
<td>History</td>
<td>Science</td>
<td>Art</td>
<td>Geography</td>
<td>Chemistry</td>
<td>Physics</td>
<td>PE</td>
<td>Biology</td>
</tr>
<tr>
<td>10:00 - 11:00</td>
<td>History</td>
<td>Geography</td>
<td>English</td>
<td>Math</td>
<td>PE</td>
<td>Science</td>
<td>Art</td>
<td>Math</td>
<td>History</td>
<td>Geography</td>
</tr>
<tr>
<td>11:00 - 12:00</td>
<td>Science</td>
<td>Math</td>
<td>History</td>
<td>Art</td>
<td>PE</td>
<td>Geography</td>
<td>Chemistry</td>
<td>Physics</td>
<td>Biology</td>
<td>Math</td>
</tr>
<tr>
<td>12:00 - 01:00</td>
<td>Art</td>
<td>Science</td>
<td>Geography</td>
<td>History</td>
<td>Math</td>
<td>English</td>
<td>PE</td>
<td>Chemistry</td>
<td>Physics</td>
<td>Biology</td>
</tr>
<tr>
<td>01:00 - 02:00</td>
<td>PE</td>
<td>Art</td>
<td>Math</td>
<td>Geography</td>
<td>Biology</td>
<td>PE</td>
<td>Physics</td>
<td>Chemistry</td>
<td>Math</td>
<td>English</td>
</tr>
</table>

</body>
</html>
3) Write a HTML program, to explain the working of forms by designing
Registration form.
(Note: Include text field, password field, number field, date of birth field,
checkboxes, radio buttons, list boxes using <select>&<option> tags, <text
area> and two buttons ie: submit and reset. Use tables to provide a better
view).

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registration Form</title>
<!-- <style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
table {
width: 60%;
margin: 0 auto;
border-collapse: collapse;
}
td {
padding: 10px;
}
th {
text-align: left;
padding: 10px;
background-color: #f2f2f2;
}
input, select, textarea {
width: 100%;
padding: 8px;
margin: 5px 0;
border: 1px solid #ccc;
border-radius: 5px;
}
textarea {
resize: vertical;
}
.form-container {
width: 80%;
margin: auto;
}
h2 {
color: #333;
}
.buttons {
text-align: center;
margin-top: 20px;
}
</style> -->
</head>
<body>

<h1>Registration Form</h1>

<div class="form-container">
<form action="#" method="post">
<table border="1" cellpadding="10">
<!-- Name -->
<tr>
<th>Name:</th>
<td><input type="text" name="name" placeholder="Enter your full name"
required></td>
</tr>

<!-- Email -->


<tr>
<th>Email:</th>
<td><input type="email" name="email" placeholder="Enter your email"
required></td>
</tr>

<!-- Password -->


<tr>
<th>Password:</th>
<td><input type="password" name="password" placeholder="Enter your password"
required></td>
</tr>
<!-- Age -->
<tr>
<th>Age:</th>
<td><input type="number" name="age" placeholder="Enter your age" min="18"
max="100" required></td>
</tr>

<!-- Date of Birth -->


<tr>
<th>Date of Birth:</th>
<td><input type="date" name="dob" required></td>
</tr>

<!-- Gender (Radio Buttons) -->


<tr>
<th>Gender:</th>
<td>
<input type="radio" name="gender" value="Male" required> Male
<input type="radio" name="gender" value="Female" required> Female
<input type="radio" name="gender" value="Other" required> Other
</td>
</tr>

<!-- Hobbies (Checkboxes) -->


<tr>
<th>Hobbies:</th>
<td>
<input type="checkbox" name="hobbies" value="Reading"> Reading
<input type="checkbox" name="hobbies" value="Traveling"> Traveling
<input type="checkbox" name="hobbies" value="Sports"> Sports
<input type="checkbox" name="hobbies" value="Music"> Music
</td>
</tr>

<!-- Country (List Box) -->


<tr>
<th>Country:</th>
<td>
<select name="country">
<option value="India">India</option>
<option value="USA">USA</option>
<option value="UK">UK</option>
<option value="Australia">Australia</option>
<option value="Canada">Canada</option>
</select>
</td>
</tr>

<!-- Comments (Text Area) -->


<tr>
<th>Comments:</th>
<td><textarea name="comments" rows="4" placeholder="Enter any additional
comments..."></textarea></td>
</tr>
</table>

<!-- Buttons -->


<div class="buttons">
<button type="submit">Submit</button>
<button type="reset">Reset</button>
</div>

4.1)
Write a HTML program, to explain the working of frames, such that page is
to be divided into 3 parts on either direction. (Note: first frame  image,
second frame  paragraph, third frame  hyperlink. And also make sure of
using “no frame” attribute such that frames to be fixed).

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Frames Layout</title>
</head>
<body>

<!-- Define the frameset for 3 columns (left image, middle paragraph, right hyperlink) -->
<frameset cols="30%, 40%, 30%" border="5">
<!-- First Frame: Image -->
<frame src="image.html" name="image_frame">

<!-- Second Frame: Paragraph -->


<frame src="paragraph.html" name="paragraph_frame">

<!-- Third Frame: Hyperlink -->


<frame src="link.html" name="link_frame">
</frameset>

<!-- Fallback content for browsers that do not support frames -->
<noframes>
<body>
<h1>This website uses frames, but your browser does not support frames.</h1>
<p>Please upgrade your browser or view this page in a browser that supports
frames.</p>
</body>
</noframes>

</body>
</html>

4.2)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Frames Example</title>
</head>
<body>

<frameset rows="33%, 34%, 33%">


<!-- First Frame: Image -->
<frame src="image.html" name="imageFrame">

<!-- Second Frame: Paragraph -->


<frame src="paragraph.html" name="paragraphFrame">

<!-- Third Frame: Hyperlink -->


<frame src="hyperlink.html" name="linkFrame">
</frameset>

<noframes>
<body>
<h2>Your browser does not support frames.</h2>
<p>Please upgrade your browser to view this content.</p>
</body>
</noframes>

</body>
</html>
EXERCISE:3
1) Write a HTML program, that makes use of <article>, <aside>, <figure>,
<figcaption>,<footer>, <header>, <main>, <nav>, <section>, <div>,
<span> tags.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML5 Semantic Tags Example</title>
<!-- <style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
}
header, footer {
background-color: #333;
color: white;
padding: 10px 0;
text-align: center;
}
nav {
background-color: #444;
padding: 10px;
margin: 10px 0;
text-align: center;
}

nav a {
color: white;
margin: 0 15px;
text-decoration: none;
}

main {
display: flex;
justify-content: space-between;
padding: 20px;
}

section, article {
background-color: white;
padding: 20px;
margin: 10px;
width: 48%;
}
aside {
background-color: #e4e4e4;
padding: 15px;
width: 30%;
}

footer {
position: fixed;
bottom: 0;
width: 100%;
}

figure {
text-align: center;
margin: 20px 0;
}

figcaption {
font-style: italic;
margin-top: 10px;

.container {
display: flex;
justify-content: space-between;
flex-wrap: wrap;
}
.box {
background-color: lightblue;
padding: 15px;
margin: 10px;
width: 48%;
}

.highlight {
background-color: yellow;
}
</style> -->
</head>
<body>

<header>
<h1>Welcome to Our Website</h1>
<p>Your go-to place for learning web development</p>
</header>

<nav>
<a href="#home">Home</a>
<a href="#about">About Us</a>
<a href="#services">Services</a>
<a href="#contact">Contact</a>
</nav>
<main>
<section>
<h2>Introduction to Web Development</h2>
<p>Web development involves the creation of websites and web applications. It
encompasses everything from building a simple static page to developing complex web
applications.</p>
</section>

<article>
<h2>Article: Understanding HTML5 Tags</h2>
<p>HTML5 introduced many new semantic tags, such as <code>&lt;article&gt;</code>,
<code>&lt;section&gt;</code>, and <code>&lt;nav&gt;</code>, which help organize content
and improve accessibility.</p>
</article>

<aside>
<h3>Related Resources</h3>
<p>Check out these links to learn more about web development:</p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/HTML">MDN HTML
Documentation</a></li>
<li><a href="https://www.w3schools.com/">W3Schools</a></li>
<li><a href="https://www.freecodecamp.org/">FreeCodeCamp</a></li>
</ul>
</aside>
</main>
<div class="container">
<div class="box">
<h3>Box 1</h3>
<p>This is a div element used for grouping content. It’s a generic container without
semantic meaning.</p>
</div>

<div class="box highlight">


<h3>Box 2 (Highlighted)</h3>
<p>This div element has a special background color using the <code>highlight</code>
class.</p>
</div>
</div>

<footer>
<p>&copy; 2024 WebDev Academy. All Rights Reserved.</p>
</footer>

</body>
</html>

2) Write a HTML program, to embed audio and video into HTML web
page.
3)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Embedding Audio and Video</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 30px;
}
.media-container {
margin-top: 20px;
}
video, audio {
width: 80%;
max-width: 600px;
margin: 20px 0;
}
</style>
</head>
<body>

<h1>Embedding Audio and Video in HTML5</h1>

<div class="media-container">
<h2>Embedded Audio Example</h2>
<!-- Audio element -->
<audio controls>
<source src="audio_sample.mp3" type="audio/mp3">
Your browser does not support the audio element.
</audio>
</div>

<div class="media-container">
<h2>Embedded Video Example</h2>
<!-- Video element -->
<video controls>
<source src="video_sample.mp4" type="video/mp4">
Your browser does not support the video element.
</video>
</div>

</body>
</html>
4) Write a program to apply different types (or levels of styles or style
specification formats) - inline, internal, external styles to HTML
elements. (identify selector, property and value).

Key Differences between Inline, Internal, and External CSS:


Feature Inline CSS Internal CSS External CSS

Inside an HTML
Where Inside the <style> tag in In an external .css file, linked
element using the style
Defined the <head> section. via <link> tag.
attribute.

Affects all matching


Affects only the Affects all matching elements
Scope elements within the
element it is applied to. across multiple pages.
document.

Quick styles for Styles specific to a single Styles shared across multiple
Use Case
individual elements. page. pages or a whole website.

Medium specificity
Highest specificity Low specificity (can be
(applies to matching
Specificity (applies directly to an overridden by inline or internal
elements in the
element). styles).
document).

@import url('styles.css'); or
<p style="color: <style> p {color: blue;}
Example <link rel="stylesheet"
red;">This is red</p> </style>
href="styles.css">

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Style Types</title>
<style>

h1 {
color: blue;
font-family: Arial, sans-serif;
}

p{
font-size: 16px;
line-height: 1.6;
}

.external-example {
background-color: #f0f0f0;
padding: 10px;
border: 1px solid #ccc;
}
</style>

</head>
<body>

<h1>This is a Heading styled with Internal CSS</h1>


<p>This paragraph uses <strong>internal CSS</strong> styles. It's part of the page's main
styles.</p>
<!-- External CSS: Reference an external style sheet (explained below) -->
<p class="external-example">This paragraph is styled with an external CSS file (explained
below).</p>

<!-- Inline CSS (in the HTML tag) -->


<p style="color: red; font-size: 18px; font-family: Verdana;">This paragraph uses
<strong>inline CSS</strong>. The styles are applied directly to this element.</p>

<div style="background-color: lightblue; padding: 15px; margin-top: 20px;">


<p>This is a <strong>div</strong> element styled using inline CSS.</p>
</div>

</body>
</html>
EXERCISE-4

1) Write a program to apply different types of selector forms


i. Simple selector (element, id, class, group, universal)
ii. Combinator selector (descendant, child, adjacent sibling, general sibling)
iii. Pseudo-class selector
iv. Pseudo-element selector
v. Attribute selector

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Selector Types</title>
<style>
/* Simple Selectors */

/* 1. Element Selector */
p{
color: blue; /* Selects all <p> elements */
}
/* 2. ID Selector */
#special {
font-weight: bold; /* Selects the element with ID "special" */
}

/* 3. Class Selector */
.highlight {
background-color: yellow; /* Selects all elements with the class "highlight" */
}

/* 4. Group Selector */
h1, h2, h3 {
font-family: 'Arial', sans-serif; /* Applies to <h1>, <h2>, and <h3> elements */
}

/* 5. Universal Selector */
*{
margin: 0; /* Selects all elements in the page */
}

/* Combinator Selectors */

/* 1. Descendant Selector */
div p {
color: green; /* Selects all <p> elements inside <div> */
}
/* 2. Child Selector */
div > p {
color: red; /* Selects all <p> elements that are direct children of <div> */
}

/* 3. Adjacent Sibling Selector */


h2 + p {
font-style: italic; /* Selects the <p> element that immediately follows an <h2> element */
}

/* 4. General Sibling Selector */


h2 ~ p {
font-size: 18px; /* Selects all <p> elements that are siblings of an <h2> element */
}

/* Pseudo-Class Selectors */

/* 1. :hover (for mouse hover effect) */


a:hover {
color: red; /* When hovering over any <a> (link) element */
}

/* 2. :nth-child() */
li:nth-child(odd) {
background-color: #f0f0f0; /* Applies to all odd <li> elements */
}

/* 3. :first-child */
div p:first-child {
font-size: 20px; /* Selects the first <p> inside a <div> */
}

/* 4. :last-child */
div p:last-child {
font-weight: bold; /* Selects the last <p> inside a <div> */
}

/* Pseudo-Element Selectors */

/* 1. ::before */
h1::before {
content: "→ "; /* Adds an arrow before every <h1> element */
color: blue;
}

/* 2. ::after */
p::after {
content: " [Read more]"; /* Adds text after every <p> element */
color: green;
}

/* Attribute Selectors */
/* 1. [attribute] */
a[target] {
color: purple; /* Selects all <a> tags that have a "target" attribute */
}

/* 2. [attribute=value] */
input[type="text"] {
border: 2px solid #000; /* Selects all <input> elements where type is "text" */
}

/* 3. [attribute^=value] */
a[href^="https://"] {
color: green; /* Selects all <a> tags whose href attribute starts with "https://" */
}

/* 4. [attribute$=value] */
img[src$=".jpg"] {
border: 3px solid black; /* Selects all <img> elements whose src attribute ends with
".jpg" */
}

/* 5. [attribute*=value] */
a[href*="example"] {
color: orange; /* Selects all <a> tags whose href contains the word "example" */
}

</style>
</head>
<body>

<h1>CSS Selectors Demonstration</h1>

<p>This is a paragraph that will be <strong>blue</strong> due to the element selector.</p>


<p id="special">This paragraph has a <strong>bold</strong> text using the ID selector.</p>
<p class="highlight">This paragraph has a <strong>yellow</strong> background using the
class selector.</p>

<div>
<p>This <code>p</code> is inside a <code>div</code>, so it is <strong>green</strong>
due to the descendant selector.</p>
<p>This <code>p</code> is a direct child of a <code>div</code>, so it is
<strong>red</strong> due to the child selector.</p>
</div>

<h2>This is a heading 2</h2>


<p>This paragraph is immediately after an <code>h2</code>, so it is
<strong>italicized</strong> due to the adjacent sibling selector.</p>

<h2>This is another heading 2</h2>


<p>This paragraph is a sibling of an <code>h2</code>, so it is <strong>font-sized
18px</strong> due to the general sibling selector.</p>

<a href="https://www.example.com">This is a link that will turn <strong>red</strong> on


hover using the pseudo-class selector.</a>

<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>

<div>
<p>This is the first paragraph in a <div>, which has <strong>increased font size</strong>
due to the first-child pseudo-class.</p>
<p>This is the last paragraph in a <div>, which is <strong>bold</strong> due to the last-
child pseudo-class.</p>
</div>

<h1>Section Heading</h1>
<p>This paragraph has an arrow before it because of the ::before pseudo-element.</p>
<p>This paragraph will have "[Read more]" added after it because of the ::after pseudo-
element.</p>

<a href="https://www.example.com" target="_blank">This link will be


<strong>purple</strong> because it has a target attribute.</a>

<input type="text" placeholder="Enter text here"> <!-- This input has a border because of the
attribute selector -->

<img src="image.jpg" alt="Image"> <!-- This image will have a border because its src ends
with ".jpg" -->
<a href="https://example.com">Link to example.com</a>

</body>
</html>
EXERCISE-5
1) Write a program to demonstrate the various ways you can reference a color in CSS.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Color References</title>
<style>
/* Using color names */
.color-name {
background-color: skyblue;
color: white;
padding: 10px;
text-align: center;
margin: 5px;
}

/* Using Hexadecimal color values */


.hex-color {
background-color: #ff6347; /* Tomato */
color: white;
padding: 10px;
text-align: center;
margin: 5px;
}
/* Using RGB (Red, Green, Blue) */
.rgb-color {
background-color: rgb(255, 99, 71); /* RGB for Tomato */
color: white;
padding: 10px;
text-align: center;
margin: 5px;
}

/* Using RGBA (Red, Green, Blue, Alpha) */


.rgba-color {
background-color: rgba(255, 99, 71, 0.5); /* RGB with 50% transparency */
color: white;
padding: 10px;
text-align: center;
margin: 5px;
}

/* Using HSL (Hue, Saturation, Lightness) */


.hsl-color {
background-color: hsl(9, 100%, 64%); /* HSL for Tomato */
color: white;
padding: 10px;
text-align: center;
margin: 5px;
}

/* Using HSLA (Hue, Saturation, Lightness, Alpha) */


.hsla-color {
background-color: hsla(9, 100%, 64%, 0.5); /* HSL with 50% transparency */
color: white;
padding: 10px;
text-align: center;
margin: 5px;
}

/* Using RGB with percentage values */


.rgb-percent-color {
background-color: rgb(100%, 50%, 0%); /* 100% red, 50% green, 0% blue */
color: white;
padding: 10px;
text-align: center;
margin: 5px;
}

/* Using transparent color */


.transparent-color {
background-color: transparent;
color: black;
padding: 10px;
text-align: center;
margin: 5px;
}
</style>
</head>
<body>

<h1>Demonstrating Various Ways to Reference Colors in CSS</h1>

<div class="color-name">
Color Name: Skyblue
</div>

<div class="hex-color">
Hexadecimal: #ff6347 (Tomato)
</div>

<div class="rgb-color">
RGB: rgb(255, 99, 71) (Tomato)
</div>

<div class="rgba-color">
RGBA: rgba(255, 99, 71, 0.5) (Tomato with 50% transparency)
</div>

<div class="hsl-color">
HSL: hsl(9, 100%, 64%) (Tomato)
</div>
<div class="hsla-color">
HSLA: hsla(9, 100%, 64%, 0.5) (Tomato with 50% transparency)
</div>

<div class="rgb-percent-color">
RGB with Percent: rgb(100%, 50%, 0%) (Orange-ish)
</div>

<div class="transparent-color">
Transparent Background (No color)
</div>

</body>
</html>
2) Write a CSS rule that places a background image halfway down the
page, tilting it horizontally. The image should remain in place when the
user scrolls up or down.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fixed Background Image with Tilt</title>
<style>
body {
background-image: url('./img2.jpg');
background-position: center 50%; /* Horizontally centered and vertically halfway */
background-attachment: fixed; /* Keeps the background fixed when scrolling */
background-size: cover; /* Ensures the image covers the entire page */
transform: rotate(45deg); /* Tilts the background image by 45 degrees */
height: 100vh; /* Makes sure the body takes full viewport height */
margin: 0; /* Removes default margin */
}
</style>
</head>
<body>
<h1>Fixed and Tilted Background Image</h1>
<p>This background stays in place when scrolling, and is tilted at an angle.</p>
</body>
</html>
3) Write a program using the following terms related to CSS font and text:
i. font-size ii. font-weight iii. font-style
iv. text-decoration v. text-transformation vi. text-alignment

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Font and Text Properties</title>
<style>
/* Set up a container for better control */
.text-container {
width: 80%;
margin: 20px auto;
padding: 20px;
border: 2px solid #ccc;
text-align: center; /* Default text alignment */
}

/* 1. Font Size */
.font-size {
font-size: 32px; /* Larger text size */
margin-bottom: 20px;
}
/* 2. Font Weight */
.font-weight {
font-weight: bold; /* Makes text bold */
margin-bottom: 20px;
}

/* 3. Font Style */
.font-style {
font-style: italic; /* Italic text */
margin-bottom: 20px;
}

/* 4. Text Decoration */
.text-decoration {
text-decoration: underline; /* Underlined text */
margin-bottom: 20px;
}

/* 5. Text Transformation */
.text-transform {
text-transform: uppercase; /* Converts text to uppercase */
margin-bottom: 20px;
}

/* 6. Text Alignment */
.text-align-left {

text-align: left; /* Aligns text to the left */


margin-bottom: 20px;
}

.text-align-right {
text-align: right; /* Aligns text to the right */
margin-bottom: 20px;
}

.text-align-center {
text-align: center; /* Centers the text */
margin-bottom: 20px;
}

.text-align-justify {
text-align: justify; /* Justifies the text */
margin-bottom: 20px;
}

</style>
</head>
<body>

<div class="text-container">
<div class="font-size">
<p>This text demonstrates <strong>font-size</strong>. The size of this text is 32px.</p>
</div>
<div class="font-weight">
<p>This text demonstrates <strong>font-weight</strong>. The text is bold.</p>
</div>

<div class="font-style">
<p>This text demonstrates <strong>font-style</strong>. The text is italicized.</p>
</div>

<div class="text-decoration">
<p>This text demonstrates <strong>text-decoration</strong>. The text is underlined.</p>
</div>

<div class="text-transform">
<p>This text demonstrates <strong>text-transform</strong>. The text is in
uppercase.</p>
</div>

<div class="text-align-left">
<p>This text demonstrates <strong>text-align: left</strong>. The text is aligned to the
left.</p>
</div>

<div class="text-align-right">
<p>This text demonstrates <strong>text-align: right</strong>. The text is aligned to the
right.</p>
</div>
<div class="text-align-center">
<p>This text demonstrates <strong>text-align: center</strong>. The text is centered.</p>
</div>

<div class="text-align-justify">
<p>This text demonstrates <strong>text-align: justify</strong>. The text is justified
(evenly spaced).</p>
</div>
</div>

</body>
</html>

3)Write a program, to explain the importance of CSS Box model using


i. Content ii. Border iii. Margin iv. Padding.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Box Model</title>
<style>
/* Styling the container box to illustrate the box model */
.box {
width: 300px; /* Content width */
padding: 20px; /* Padding around the content */
border: 5px solid blue; /* Border around the padding */
margin: 30px; /* Space between the box and other elements */
background-color: lightgray; /* Background color for the content area */
}

.box2 {
width: 200px;
padding: 10px;
border: 3px dashed red;
margin: 15px;
background-color: lightyellow;
}

.box3 {
width: 400px;
padding: 40px;
border: 10px double green;
margin: 50px;
background-color: lightpink;
}

/* Additional style to make the visual more obvious */


p{
text-align: center;
font-size: 18px;
font-family: Arial, sans-serif;
}
</style>
</head>
<body>

<h1 style="text-align:center;">CSS Box Model Demonstration</h1>

<!-- Box 1 -->


<div class="box">
<p>Box 1: Content, Padding, Border, and Margin</p>
</div>

<!-- Box 2 -->


<div class="box2">
<p>Box 2: Different Box Model Styles</p>
</div>

<!-- Box 3 -->


<div class="box3">
<p>Box 3: Larger Box Model Example</p>
</div>

</body> </html>
EXERCISE-6
1) Write a program to embed internal and external JavaScript in a web page.
HTML FILE:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Example: Internal & External</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}

button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
</style>

<!-- Internal JavaScript -->


<script>
// This is an internal JavaScript function
function greetUser() {
alert("Hello, welcome to the page!");
}
</script>

</head>
<body>
<h1>JavaScript Example: Internal and External</h1>
<p>This example demonstrates both internal and external JavaScript.</p>

<!-- Button to trigger internal JavaScript -->


<button onclick="greetUser()">Click me (Internal JS)</button>

<br><br>
<!-- Button to trigger external JavaScript -->
<button onclick="changeColor()">Click me (External JS)</button>
<!-- External JavaScript File -->
<script src="one.js"></script>
</body>
</html>

JAVA SCRIPT FILE:-

function changeColor() {
document.body.style.backgroundColor = "#f0f8ff";
alert("Background color changed to light blue!");
}
2) Write a program to explain the different ways for displaying output.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Different Ways to Display Output</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
#outputDiv {
margin-top: 20px;
padding: 20px;
border: 2px dashed #4CAF50;
}
</style>
</head>
<body>

<h1>Different Ways to Display Output in JavaScript</h1>

<button onclick="showAlert()">Show Alert</button>


<button onclick="writeToDocument()">Write to Document</button>
<button onclick="logToConsole()">Log to Console</button>
<button onclick="changeContent()">Change Content of HTML Element</button>
<div id="outputDiv">
<h3>Content will change here:</h3>
<p id="content">This is the original content.</p>
</div>
<script>
// 1. Using alert() - Displays an alert box
function showAlert() {
alert("This is an alert box!"); // This will pop up an alert box with the message
}
// 2. Using document.write() - Writes directly to the HTML document
function writeToDocument() {
document.write("<h2>This is written using document.write().</h2>");
}
// 3. Using console.log() - Logs to the developer console
function logToConsole() {
console.log("This message is logged to the browser's console."); // Open the browser
console to see this
}
// 4. Using innerHTML - Modifies the content of an HTML element
function changeContent() {
document.getElementById("content").innerHTML = "The content has been changed
using innerHTML!";
}
</script>

</body>
</html>
3) Write a program to explain the different ways for taking input.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Different Ways to Take Input in JavaScript</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}

input, select, button, textarea {


padding: 10px;
margin: 10px;
font-size: 16px;
}

#output {
margin-top: 20px;
padding: 20px;
border: 2px dashed #4CAF50;
font-size: 18px;
}
</style>
</head>
<body>

<h1>Different Ways to Take Input in JavaScript</h1>

<!-- Using prompt() -->


<button onclick="promptInput()">Prompt Input</button>

<br><br>

<!-- Using HTML Input Element -->


<input type="text" id="nameInput" placeholder="Enter your name">
<button onclick="getInputValue()">Get Name from Input</button>

<br><br>

<!-- Using HTML Textarea Element -->


<textarea id="messageInput" placeholder="Type your message here..."></textarea>
<button onclick="getMessageInput()">Get Message from Textarea</button>

<br><br>

<!-- Using HTML Select Element -->


<select id="colorSelect">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<button onclick="getColorInput()">Get Selected Color</button>
<div id="output"></div>

<script>
// 1. Using prompt() to take input from the user
function promptInput() {
var userInput = prompt("Please enter your favorite color:");
if (userInput != null) {
document.getElementById("output").innerHTML = "You entered: " + userInput;
} else {
document.getElementById("output").innerHTML = "No input was provided.";
}
}

// 2. Using HTML Input Element to take input from the user


function getInputValue() {
var name = document.getElementById("nameInput").value;
document.getElementById("output").innerHTML = "Hello, " + name + "!";
}

// 3. Using HTML Textarea Element to take input from the user


function getMessageInput() {
var message = document.getElementById("messageInput").value;
document.getElementById("output").innerHTML = "Your message: " + message;
}

// 4. Using HTML Select Element to take input from the user


function getColorInput() {
var color = document.getElementById("colorSelect").value;
document.getElementById("output").innerHTML = "You selected the color: " + color;
}
</script>

</body>
</html>

4) Create a webpage which uses prompt dialogue box to ask a voter for his
name and age. Display the information in table format along with either the
voter can vote or not.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voter Eligibility Check</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
table {
width: 50%;
margin: 20px auto;
border-collapse: collapse;
border: 1px solid #ddd;
}
th, td {
padding: 10px;
text-align: left;
border: 1px solid #ddd;
}
th {
background-color: #f2f2f2;
}
#output {
margin-top: 20px;
font-size: 18px;
}
</style>
</head>
<body>

<h1>Voter Eligibility Check</h1>


<button onclick="checkEligibility()">Check Eligibility</button>

<div id="output"></div>

<script>
// Function to check voter eligibility
function checkEligibility() {
// Prompt the user for their name and age
var name = prompt("Please enter your name:");
var age = prompt("Please enter your age:");
// Check if the name and age are valid
if (name && age) {
age = parseInt(age); // Convert age to an integer

// Create a message based on the age


var eligibility = (age >= 18) ? "Eligible to vote" : "Not eligible to vote";

// Display the information in a table format


var outputHtml = `
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Eligibility</th>
</tr>
<tr>
<td>${name}</td>
<td>${age}</td>
<td>${eligibility}</td>
</tr>
</table>
`;
document.getElementById("output").innerHTML = outputHtml;
} else {
alert("Please enter valid information.");
}}</script</body></html>

EXERCISE-7
1) Write a program using document object properties and methods.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document Object Methods & Properties</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
#message {
margin-top: 20px;
font-size: 18px;
}
.highlight {
color: red;
}
</style>
</head>
<body>
<h1>Document Object Model (DOM) Methods and Properties</h1>

<p id="intro">This is an example of using various document object methods and


properties.</p>
<button onclick="changeContent()">Change Content</button>
<button onclick="addNewElement()">Add New Element</button>
<button onclick="highlightText()">Highlight Text</button>

<div id="message"></div>

<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>

<script>
// 1. Using document.getElementById() to change content
function changeContent() {
var intro = document.getElementById("intro");
intro.innerHTML = "The content has been changed using
<strong>getElementById()</strong>!";
document.getElementById("message").innerHTML = "You successfully changed the
content!";
}

// 2. Using document.createElement() and appendChild() to add a new element


function addNewElement() {
var newElement = document.createElement("p"); // Create a new <p> element
newElement.innerHTML = "This is a new paragraph added dynamically!";
document.body.appendChild(newElement); // Append the new element to the body
}

// 3. Using document.getElementsByClassName() to highlight text


function highlightText() {
var items = document.getElementsByClassName("highlight");
for (var i = 0; i < items.length; i++) {
items[i].style.color = "blue"; // Change text color of each highlighted item
}
}

// 4. Using document.querySelector() and querySelectorAll()


function highlightText() {
var firstItem = document.querySelector("li"); // Selects the first <li> element
firstItem.style.backgroundColor = "yellow"; // Adds a background color to the first <li>

// Select all <li> elements and change their text color


var allItems = document.querySelectorAll("li");
allItems.forEach(function(item) {
item.style.color = "green"; // Change text color to green for all <li> items
});
}
</script>
</body>
</html>
2) Write a program using window object properties and methods.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Window Object Methods and Properties</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
button {
padding: 10px 20px;
font-size: 16px;
margin: 10px;
cursor: pointer;
}
#output {
margin-top: 20px;
font-size: 18px;
}
</style>
</head>
<body>

<h1>Window Object Methods and Properties</h1>


<button onclick="showAlert()">Show Alert</button>
<button onclick="showConfirm()">Show Confirm</button>
<button onclick="showPrompt()">Show Prompt</button>
<button onclick="openNewWindow()">Open New Window</button>
<button onclick="showWindowSize()">Show Window Size</button>
<button onclick="scrollToTop()">Scroll to Top</button>
<button onclick="redirectToGoogle()">Redirect to Google</button>
<button onclick="closeWindow()">Close Window (if opened)</button>

<div id="output"></div>

<script>
// 1. Show an alert box
function showAlert() {
window.alert("This is an alert message!");
}

// 2. Show a confirm dialog and check user response


function showConfirm() {
var result = window.confirm("Do you want to continue?");
document.getElementById("output").innerHTML = result ? "User clicked OK" : "User
clicked Cancel";
}

// 3. Show a prompt and display the entered value


function showPrompt() {
var userInput = window.prompt("Please enter your name:");
if (userInput != null) {
document.getElementById("output").innerHTML = "Hello, " + userInput + "!";
} else {
document.getElementById("output").innerHTML = "User canceled the prompt.";
}
}

// 4. Open a new browser window or tab


function openNewWindow() {
window.open("https://www.example.com", "_blank"); // Open in a new tab
}

// 5. Show the current window size (width and height)


function showWindowSize() {
var width = window.innerWidth;
var height = window.innerHeight;
document.getElementById("output").innerHTML = `Window size: ${width}px (Width) x
${height}px (Height)`;
}

// 6. Scroll to the top of the page


function scrollToTop() {
window.scrollTo(0, 0);
}

// 7. Redirect to Google
function redirectToGoogle() {
window.location.href = "https://www.google.com"; // Redirect to Google
}
// 8. Close the current window (if opened via script)
function closeWindow() {
window.close();
}
</script>

</body>
</html>
3) Write a program using array object properties and methods.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Array Methods and Properties</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
margin: 10px;
}
#output {
margin-top: 20px;
font-size: 18px;
}
</style>
</head>
<body>

<h1>Array Object Methods and Properties</h1>


<button onclick="demonstrateArrayMethods()">Demonstrate Array Methods</button>

<div id="output"></div>

<script>
// Array to work with
var fruits = ["Apple", "Banana", "Orange", "Mango", "Grapes"];

// Function to demonstrate various array methods and properties


function demonstrateArrayMethods() {
var outputHtml = "";

// 1. Array Length Property


outputHtml += "<strong>Array Length:</strong> " + fruits.length + "<br>";

// 2. push() - Adding an element to the end of the array


fruits.push("Pineapple");
outputHtml += "<strong>After push('Pineapple'):</strong> " + fruits.join(", ") + "<br>";

// 3. pop() - Removing the last element of the array


var popped = fruits.pop();
outputHtml += "<strong>After pop() (Removed: " + popped + "):</strong> " +
fruits.join(", ") + "<br>";

// 4. shift() - Removing the first element of the array


var shifted = fruits.shift();
outputHtml += "<strong>After shift() (Removed: " + shifted + "):</strong> " +
fruits.join(", ") + "<br>";
// 5. unshift() - Adding an element to the beginning of the array
fruits.unshift("Strawberry");
outputHtml += "<strong>After unshift('Strawberry'):</strong> " + fruits.join(", ") +
"<br>";

// 6. concat() - Combining two arrays


var moreFruits = ["Pomegranate", "Blueberry"];
var combinedFruits = fruits.concat(moreFruits);
outputHtml += "<strong>After concat(['Pomegranate', 'Blueberry']):</strong> " +
combinedFruits.join(", ") + "<br>";

// 7. slice() - Extracting a section of the array


var slicedFruits = fruits.slice(1, 3); // Extracts from index 1 to 2 (not including 3)
outputHtml += "<strong>After slice(1, 3):</strong> " + slicedFruits.join(", ") + "<br>";

// 8. splice() - Removing or adding elements at a specific index


var splicedFruits = fruits.splice(2, 1, "Kiwi", "Peach"); // Removes 1 item at index 2 and
adds two items
outputHtml += "<strong>After splice(2, 1, 'Kiwi', 'Peach'):</strong> " + fruits.join(", ") +
"<br>";

// 9. forEach() - Executing a function for each element


outputHtml += "<strong>Using forEach() to display all fruits:</strong><br>";
fruits.forEach(function(fruit, index) {
outputHtml += "Index " + index + ": " + fruit + "<br>";
});

// 10. map() - Creating a new array by transforming each element


var fruitLengths = fruits.map(function(fruit) {
return fruit.length; // Create a new array with the length of each fruit's name
});
outputHtml += "<strong>Using map() to get the length of each fruit's name:</strong> " +
fruitLengths.join(", ") + "<br>";

// 11. filter() - Creating a new array with elements that meet a condition
var longFruits = fruits.filter(function(fruit) {
return fruit.length > 5; // Get fruits with names longer than 5 characters
});
outputHtml += "<strong>Using filter() to get fruits with names longer than 5
characters:</strong> " + longFruits.join(", ") + "<br>";

// 12. reduce() - Reducing the array to a single value (concatenate all fruit names)
var allFruits = fruits.reduce(function(accumulator, currentValue) {
return accumulator + " " + currentValue; // Concatenate all fruit names into one string
}, "");
outputHtml += "<strong>Using reduce() to concatenate all fruit names:</strong> " +
allFruits + "<br>";

// Display the output


document.getElementById("output").innerHTML = outputHtml;
}
</script>

</body>
</html>
4) Write a program using math object properties and methods.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Math Object Methods and Properties</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
margin: 10px;
}
#output {
margin-top: 20px;
font-size: 18px;
}
</style>
</head>
<body>
<h1>Math Object Methods and Properties</h1>

<button onclick="demonstrateMathMethods()">Demonstrate Math Methods</button>

<div id="output"></div>

<script>
function demonstrateMathMethods() {
var outputHtml = "";

// 1. Math.PI - Value of Pi
outputHtml += "<strong>Math.PI:</strong> " + Math.PI + "<br>";

// 2. Math.E - Value of Euler's number (e)


outputHtml += "<strong>Math.E:</strong> " + Math.E + "<br>";

// 3. Math.abs() - Absolute value of a number


var num = -15.5;
outputHtml += "<strong>Math.abs(" + num + "):</strong> " + Math.abs(num) + "<br>";

// 4. Math.pow() - Power of a number


var base = 2;
var exponent = 3;
outputHtml += "<strong>Math.pow(" + base + ", " + exponent + "):</strong> " +
Math.pow(base, exponent) + "<br>";

// 5. Math.sqrt() - Square root of a number


var squareRootNumber = 64;
outputHtml += "<strong>Math.sqrt(" + squareRootNumber + "):</strong> " +
Math.sqrt(squareRootNumber) + "<br>";

// 6. Math.random() - Random number between 0 and 1


outputHtml += "<strong>Math.random() (random number between 0 and 1):</strong> "
+ Math.random() + "<br>";

// 7. Math.round() - Round a number to the nearest integer


var roundNumber = 4.6;
outputHtml += "<strong>Math.round(" + roundNumber + "):</strong> " +
Math.round(roundNumber) + "<br>";

// 8. Math.ceil() - Round a number upwards to the nearest integer


var ceilNumber = 4.1;
outputHtml += "<strong>Math.ceil(" + ceilNumber + "):</strong> " +
Math.ceil(ceilNumber) + "<br>";

// 9. Math.floor() - Round a number downwards to the nearest integer


var floorNumber = 4.9;
outputHtml += "<strong>Math.floor(" + floorNumber + "):</strong> " +
Math.floor(floorNumber) + "<br>";

// 10. Math.max() - Maximum of two or more numbers


outputHtml += "<strong>Math.max(5, 10, 15, 20):</strong> " + Math.max(5, 10, 15, 20)
+ "<br>";

// 11. Math.min() - Minimum of two or more numbers


outputHtml += "<strong>Math.min(5, 10, 15, 20):</strong> " + Math.min(5, 10, 15, 20)
+ "<br>";

// 12. Math.sin() - Sine of a number (in radians)


var angleInRadians = Math.PI / 2; // 90 degrees in radians
outputHtml += "<strong>Math.sin(" + angleInRadians + "):</strong> " +
Math.sin(angleInRadians) + "<br>";

// 13. Math.cos() - Cosine of a number (in radians)


var angleInRadiansCos = Math.PI; // 180 degrees in radians
outputHtml += "<strong>Math.cos(" + angleInRadiansCos + "):</strong> " +
Math.cos(angleInRadiansCos) + "<br>";

// 14. Math.tan() - Tangent of a number (in radians)


var angleInRadiansTan = Math.PI / 4; // 45 degrees in radians
outputHtml += "<strong>Math.tan(" + angleInRadiansTan + "):</strong> " +
Math.tan(angleInRadiansTan) + "<br>";

// Display the output


document.getElementById("output").innerHTML = outputHtml;
}
</script>

</body>
</html>
5) Write a program using string object properties and methods.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>String Object Methods and Properties</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
margin: 10px;
}
#output {
margin-top: 20px;
font-size: 18px;
}
</style>
</head>
<body>

<h1>String Object Methods and Properties</h1>


<button onclick="demonstrateStringMethods()">Demonstrate String Methods</button>

<div id="output"></div>

<script>
function demonstrateStringMethods() {
var outputHtml = "";

// Sample string for demonstration


var str = " Hello, JavaScript World! ";

// 1. length - Get the length of the string


outputHtml += "<strong>Length of string:</strong> " + str.length + "<br>";

// 2. charAt() - Get the character at a specified index


outputHtml += "<strong>Character at index 7:</strong> " + str.charAt(7) + "<br>";

// 3. indexOf() - Find the first occurrence of a substring


outputHtml += "<strong>Index of 'JavaScript':</strong> " + str.indexOf("JavaScript") +
"<br>";

// 4. lastIndexOf() - Find the last occurrence of a substring


outputHtml += "<strong>Last index of 'o':</strong> " + str.lastIndexOf("o") + "<br>";

// 5. slice() - Extract a portion of the string


outputHtml += "<strong>Slice from index 7 to 18:</strong> " + str.slice(7, 18) + "<br>";

// 6. substring() - Extract a substring between two indices


outputHtml += "<strong>Substring from index 7 to 18:</strong> " + str.substring(7, 18)
+ "<br>";

// 7. toLowerCase() - Convert the string to lowercase


outputHtml += "<strong>Lowercase string:</strong> " + str.toLowerCase() + "<br>";

// 8. toUpperCase() - Convert the string to uppercase


outputHtml += "<strong>Uppercase string:</strong> " + str.toUpperCase() + "<br>";

// 9. replace() - Replace a part of the string with another string


outputHtml += "<strong>Replace 'JavaScript' with 'Programming':</strong> " +
str.replace("JavaScript", "Programming") + "<br>";

// 10. split() - Split the string into an array based on a separator


var splitArray = str.split(" ");
outputHtml += "<strong>Split the string by space:</strong> " + splitArray.join(", ") +
"<br>";

// 11. trim() - Remove whitespace from both ends of the string


outputHtml += "<strong>Trimmed string:</strong> '" + str.trim() + "'<br>";

// 12. concat() - Concatenate two or more strings


var extraStr = " Let's learn more!";
outputHtml += "<strong>Concatenated string:</strong> " + str.concat(extraStr) + "<br>";

// 13. charCodeAt() - Get the Unicode value of the character at a specified index
outputHtml += "<strong>Unicode value of character at index 7:</strong> " +
str.charCodeAt(7) + "<br>";

// 14. includes() - Check if the string contains a specific substring


outputHtml += "<strong>Does the string contain 'JavaScript'?</strong> " +
str.includes("JavaScript") + "<br>";

// Display the output


document.getElementById("output").innerHTML = outputHtml;
}
</script>

</body>
</html>

6) Write a program using regex object properties and methods.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>RegExp Object Methods and Properties</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
margin: 10px;
}
#output {
margin-top: 20px;
font-size: 18px;
}
</style>
</head>
<body>

<h1>RegExp Object Methods and Properties</h1>

<button onclick="demonstrateRegExpMethods()">Demonstrate RegExp Methods</button>

<div id="output"></div>

<script>
function demonstrateRegExpMethods() {
var outputHtml = "";

// 1. Regular Expression: Pattern for testing email validation


var emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var testEmail = "[email protected]";

// 2. test() - Test if the pattern matches the string


outputHtml += "<strong>test() - Testing if '" + testEmail + "' is a valid email:</strong> "
+ emailPattern.test(testEmail) + "<br>";
// 3. exec() - Get more details about the match (useful with global searches)
var execResult = emailPattern.exec(testEmail);
outputHtml += "<strong>exec() - Result of matching '" + testEmail + "':</strong> " +
(execResult ? execResult : "No match found") + "<br>";

// 4. match() - Method of string object to test if the pattern matches the string
var str = "The email address is [email protected].";
var matchResult = str.match(emailPattern);
outputHtml += "<strong>match() - Matching email in string '" + str + "':</strong> " +
(matchResult ? matchResult : "No match found") + "<br>";

// 5. replace() - Replace matched text with a new string


var replacedStr = str.replace(emailPattern, "[email protected]");
outputHtml += "<strong>replace() - Replacing email in string:</strong> " + replacedStr
+ "<br>";

// 6. search() - Search for the first match and return the index of the match
var searchResult = str.search(emailPattern);
outputHtml += "<strong>search() - Searching for email in string:</strong> " +
searchResult + "<br>";

// 7. split() - Split string by matched pattern


var splitResult = str.split(emailPattern);
outputHtml += "<strong>split() - Splitting string by email pattern:</strong> " +
splitResult.join(", ") + "<br>";

// 8. lastIndex - Demonstrating the `lastIndex` property for global regex search


var globalPattern = /test/g; // 'g' flag for global search
globalPattern.lastIndex = 5; // Set the starting index for the next match
var globalSearchResult = globalPattern.exec("This is a test for testing.");
outputHtml += "<strong>lastIndex - Starting search from index 5:</strong> " +
(globalSearchResult ? globalSearchResult : "No match found") + "<br>";

// Display the output


document.getElementById("output").innerHTML = outputHtml;
}
</script>

</body>
</html>

7) Write a program using date object properties and methods.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Date Object Methods and Properties</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
margin: 10px;
}
#output {
margin-top: 20px;
font-size: 18px;
}
</style>
</head>
<body>

<h1>Date Object Methods and Properties</h1>

<button onclick="demonstrateDateMethods()">Demonstrate Date Methods</button>

<div id="output"></div>

<script>
function demonstrateDateMethods() {
var outputHtml = "";

// Create a new Date object


var currentDate = new Date();

// 1. getFullYear() - Get the current year


outputHtml += "<strong>Current Year:</strong> " + currentDate.getFullYear() + "<br>";

// 2. getMonth() - Get the current month (0-11, where 0 is January)


var month = currentDate.getMonth();
outputHtml += "<strong>Current Month (0-11):</strong> " + month + "<br>";
outputHtml += "<strong>Current Month Name:</strong> " + getMonthName(month) +
"<br>";

// 3. getDate() - Get the current day of the month (1-31)


outputHtml += "<strong>Current Day of the Month:</strong> " + currentDate.getDate()
+ "<br>";

// 4. getDay() - Get the current day of the week (0-6, where 0 is Sunday)
var day = currentDate.getDay();
outputHtml += "<strong>Current Day of the Week (0-6):</strong> " + day + "<br>";
outputHtml += "<strong>Current Day Name:</strong> " + getDayName(day) + "<br>";

// 5. getHours() - Get the current hour (0-23)


outputHtml += "<strong>Current Hour (0-23):</strong> " + currentDate.getHours() +
"<br>";

// 6. getMinutes() - Get the current minute (0-59)


outputHtml += "<strong>Current Minute (0-59):</strong> " + currentDate.getMinutes()
+ "<br>";

// 7. getSeconds() - Get the current second (0-59)


outputHtml += "<strong>Current Second (0-59):</strong> " + currentDate.getSeconds()
+ "<br>";

// 8. getMilliseconds() - Get the current millisecond (0-999)


outputHtml += "<strong>Current Millisecond (0-999):</strong> " +
currentDate.getMilliseconds() + "<br>";

// 9. getTime() - Get the current time in milliseconds since January 1, 1970


outputHtml += "<strong>Time in Milliseconds since January 1, 1970:</strong> " +
currentDate.getTime() + "<br>";

// 10. toDateString() - Get the current date in a human-readable format


outputHtml += "<strong>Current Date (Date String):</strong> " +
currentDate.toDateString() + "<br>";

// 11. toTimeString() - Get the current time in a human-readable format


outputHtml += "<strong>Current Time (Time String):</strong> " +
currentDate.toTimeString() + "<br>";

// 12. toLocaleDateString() - Get the current date formatted for the locale
outputHtml += "<strong>Current Date (Locale Date):</strong> " +
currentDate.toLocaleDateString() + "<br>";

// 13. toLocaleTimeString() - Get the current time formatted for the locale
outputHtml += "<strong>Current Time (Locale Time):</strong> " +
currentDate.toLocaleTimeString() + "<br>";

// 14. setFullYear() - Set the year to 2025


currentDate.setFullYear(2025);
outputHtml += "<strong>Updated Year (setFullYear to 2025):</strong> " +
currentDate.getFullYear() + "<br>";

// Display the output


document.getElementById("output").innerHTML = outputHtml;
}

// Helper function to get the month name


function getMonthName(monthIndex) {
const months = [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
return months[monthIndex];
}

// Helper function to get the day name


function getDayName(dayIndex) {
const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday"];
return days[dayIndex];
}
</script>

</body>
</html>
8) Write a program to explain user-defined object by using properties,
methods, accessors, constructors and display.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User-Defined Object Example: Car</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
margin: 10px;
}
#output {
margin-top: 20px;
font-size: 18px;
}
</style>
</head>
<body>
<h1>User-Defined Object Example: Car</h1>

<button onclick="createAndDisplayCar()">Create and Display Car Object</button>

<div id="output"></div>

<script>
// Constructor for Car object
function Car(make, model, year, color) {
this.make = make; // Property
this.model = model; // Property
this.year = year; // Property
this.color = color; // Property
this.currentSpeed = 0; // Property (default speed)

// Method: accelerate
this.accelerate = function() {
this.currentSpeed += 5;
};

// Method: brake
this.brake = function() {
this.currentSpeed -= 5;
if (this.currentSpeed < 0) {
this.currentSpeed = 0; // Prevent negative speed
}
};
// Getter: getCarInfo
this.getCarInfo = function() {
return `${this.year} ${this.make} ${this.model} (${this.color})`;
};

// Accessor: Get the current speed


this.getCurrentSpeed = function() {
return this.currentSpeed;
};

// Accessor: Set a new speed


this.setCurrentSpeed = function(newSpeed) {
this.currentSpeed = newSpeed >= 0 ? newSpeed : 0; // Avoid negative speed
};

// Method to display car information


this.displayCarInfo = function() {
return `Car Info: ${this.getCarInfo()}<br>Current Speed: ${this.getCurrentSpeed()}
km/h`;
};
}

// Create and display the Car object


function createAndDisplayCar() {
// Create a new Car object using the constructor
var myCar = new Car("Toyota", "Corolla", 2020, "Red");

// Accessor usage: Get the initial car information


var carInfo = myCar.displayCarInfo();

// Accelerate and brake the car


myCar.accelerate();
myCar.accelerate();
myCar.brake();

// Update and display updated car information


carInfo += "<br><br>After accelerating and braking:<br>";
carInfo += myCar.displayCarInfo();

// Display the information on the web page


document.getElementById("output").innerHTML = carInfo;
}
</script>

</body>
</html>
EXERCISE:-8
1) Write a program which asks the user to enter three integers, obtains the
numbers from the user and outputs HTML text that displays the larger
number followed by the words “LARGER NUMBER” in an
information message dialog. If the numbers are equal, output HTML
text as “EQUAL NUMBERS”.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Find the Larger Number</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
input {
margin: 10px;
padding: 5px;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
margin-top: 10px;
}
</style>
</head>
<body>

<h1>Enter Three Numbers</h1>

<label for="num1">Enter first number:</label>


<input type="number" id="num1"><br><br>

<label for="num2">Enter second number:</label>


<input type="number" id="num2"><br><br>

<label for="num3">Enter third number:</label>


<input type="number" id="num3"><br><br>

<button onclick="findLargerNumber()">Check Larger Number</button>

<script>
function findLargerNumber() {
// Get user input values
var num1 = parseInt(document.getElementById("num1").value);
var num2 = parseInt(document.getElementById("num2").value);
var num3 = parseInt(document.getElementById("num3").value);
// Check if any input is missing
if (isNaN(num1) || isNaN(num2) || isNaN(num3)) {
alert("Please enter valid numbers in all fields.");
return;
}

// Compare the numbers


if (num1 === num2 && num2 === num3) {
// If all numbers are equal
alert("EQUAL NUMBERS");
} else {
// Find the largest number
var largest = Math.max(num1, num2, num3);
alert(largest + " LARGER NUMBER");
}
}
</script>

</body>
</html>
2) Write a program to display week days using switch case.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Display Week Days</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
input {
margin: 10px;
padding: 5px;
width: 150px;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>

<h1>Enter a Number to Get the Day of the Week</h1>


<label for="dayNumber">Enter a number (1-7):</label>
<input type="number" id="dayNumber" min="1" max="7"><br><br>

<button onclick="displayDay()">Show Day</button>

<div id="output" style="margin-top: 20px; font-size: 18px;"></div>

<script>
function displayDay() {
// Get the number entered by the user
var day = parseInt(document.getElementById("dayNumber").value);

// Display the corresponding day using a switch case


var dayName;

switch(day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid input! Please enter a number between 1 and 7.";
break;
}

// Display the result on the web page


document.getElementById("output").innerHTML = "The day is: " + dayName;
}
</script>

</body>
</html>
3) Write a program to print 1 to 10 numbers using for, while and do-while
loops.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Print Numbers 1 to 10</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
margin: 10px;
}
div {
margin-top: 20px;
font-size: 18px;
margin-bottom: 10px;
}
</style>
</head>
<body>

<h1>Print Numbers 1 to 10 Using Different Loops</h1>

<button onclick="printUsingForLoop()">Print Using For Loop</button>


<button onclick="printUsingWhileLoop()">Print Using While Loop</button>
<button onclick="printUsingDoWhileLoop()">Print Using Do-While Loop</button>

<div id="output"></div>

<script>
function printUsingForLoop() {
let output = "Using For Loop: <br>";
for (let i = 1; i <= 10; i++) {
output += i + " ";
}
document.getElementById("output").innerHTML = output;
}

function printUsingWhileLoop() {
let output = "Using While Loop: <br>";
let i = 1;
while (i <= 10) {
output += i + " ";
i++;
}
document.getElementById("output").innerHTML = output;
}
function printUsingDoWhileLoop() {
let output = "Using Do-While Loop: <br>";
let i = 1;
do {
output += i + " ";
i++;
} while (i <= 10);
document.getElementById("output").innerHTML = output;
}
</script>

</body>
</html>
4) Write aprogram to print data in object using for-in, for-each and for-of
loops.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Object Looping Examples</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
margin: 10px;
}
div {
margin-top: 20px;
font-size: 18px;
margin-bottom: 10px;
}
</style>
</head>
<body>
<h1>Print Data from an Object Using Different Loops</h1>

<button onclick="printUsingForIn()">Print Using for-in Loop</button>


<button onclick="printUsingForEach()">Print Using forEach Loop</button>
<button onclick="printUsingForOf()">Print Using for-of Loop</button>

<div id="output"></div>

<script>
// Define an object with some data
const person = {
name: "John Doe",
age: 30,
job: "Software Developer",
country: "USA"
};

// Print using for-in loop


function printUsingForIn() {
let output = "Using for-in Loop: <br>";
for (let key in person) {
output += key + ": " + person[key] + "<br>";
}
document.getElementById("output").innerHTML = output;
}

// Print using forEach loop (needs Object.entries or Object.keys)


function printUsingForEach() {
let output = "Using forEach Loop: <br>";
Object.entries(person).forEach(([key, value]) => {
output += key + ": " + value + "<br>";
});
document.getElementById("output").innerHTML = output;
}

// Print using for-of loop (needs Object.entries or Object.keys)


function printUsingForOf() {
let output = "Using for-of Loop: <br>";
for (let [key, value] of Object.entries(person)) {
output += key + ": " + value + "<br>";
}
document.getElementById("output").innerHTML = output;
}
</script>

</body>
</html>
5)Develop a program to determine whether a given number is an
‘ARMSTRONGNUMBER’ or not. [Eg: 153 is an Armstrong number, since
sum of the cube of the digits is equal to the number i.e.,13 + 53+ 33 = 153]

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Armstrong Number Check</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
input {
margin: 10px;
padding: 5px;
width: 150px;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
margin-top: 10px;
}
div {
margin-top: 20px;
font-size: 18px;
margin-bottom: 10px;
}
</style>
</head>
<body>

<h1>Check if a Number is an Armstrong Number</h1>

<label for="num">Enter a number:</label>


<input type="number" id="num" required><br><br>

<button onclick="checkArmstrongNumber()">Check</button>

<div id="result"></div>

<script>
function checkArmstrongNumber() {
// Get the number from the input field
let num = parseInt(document.getElementById("num").value);
// Validate the input
if (isNaN(num)) {
document.getElementById("result").innerHTML = "Please enter a valid number!";
return;
}
// Store the original number to compare later
let originalNum = num;
let sum = 0;
let numOfDigits = num.toString().length; // Get the number of digits

// Loop through each digit of the number


while (num > 0) {
let digit = num % 10; // Extract the last digit
sum += Math.pow(digit, numOfDigits); // Add the power of the digit
num = Math.floor(num / 10); // Remove the last digit
}

// Check if the sum of the powered digits equals the original number
if (sum === originalNum) {
document.getElementById("result").innerHTML = originalNum + " is an Armstrong
number.";
} else {
document.getElementById("result").innerHTML = originalNum + " is not an
Armstrong number.";
}
}
</script>

</body>
</html>
5)Write a program to display the denomination of the amount deposited in the
bank in terms of 100’s, 50’s, 20’s, 10’s, 5’s, 2’s & 1’s. (Eg: If deposited amount
is Rs.163, the output should be 1-100’s, 1-50’s, 1- 10’s, 1-2’s & 1-1’s).

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Denomination of Amount</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
input {
padding: 5px;
margin-top: 10px;
width: 150px;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
margin-top: 10px;
}
div {
margin-top: 20px;
font-size: 18px;
margin-bottom: 10px;
word-wrap: break-word;
}
</style>
</head>
<body>

<h1>Denomination of Amount Deposited</h1>

<label for="amount">Enter the deposited amount (in Rs.):</label>


<input type="number" id="amount" required><br><br>

<button onclick="calculateDenominations()">Calculate Denominations</button>

<div id="result"></div>

<script>
function calculateDenominations() {
// Get the deposited amount from input
let amount = parseInt(document.getElementById("amount").value);
// Check if the amount is a valid number
if (isNaN(amount) || amount <= 0) {
document.getElementById("result").innerHTML = "Please enter a valid amount
greater than 0.";
return;
}
// Denominations available
let denominations = [100, 50, 20, 10, 5, 2, 1];
let result = "Denominations for Rs." + amount + " are:<br>";

// Loop through each denomination and calculate the count of each


for (let i = 0; i < denominations.length; i++) {
let count = Math.floor(amount / denominations[i]); // How many notes of current
denomination
if (count > 0) {
result += count + " x Rs." + denominations[i] + "'s<br>";
}
amount -= count * denominations[i]; // Reduce the amount by the value of the notes
used
}

document.getElementById("result").innerHTML = result;
}
</script>

</body>
</html>

EXERCISE:-9
1) Design a appropriate function should be called to display
i. Factorial of that number
ii. Fibonacci series up to that number
iii. Prime numbers up to that number
iv. Is it palindrome or not

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Number Operations</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
input {
padding: 5px;
margin-top: 10px;
width: 150px;
}
button {
padding: 10px 20px;
font-size: 16px;

cursor: pointer;
margin-top: 10px;
}
div {
margin-top: 20px;
font-size: 18px;
margin-bottom: 10px;
word-wrap: break-word;
}
</style>
</head>
<body>

<h1>Number Operations</h1>

<label for="number">Enter a number:</label>


<input type="number" id="number" required><br><br>

<button onclick="performOperations()">Perform Operations</button>

<div id="result"></div>

<script>
// Function to calculate the factorial of a number
function factorial(num) {
let result = 1;
for (let i = 1; i <= num; i++) {
result *= i;
}
return result;
}

// Function to generate the Fibonacci series up to a number


function fibonacci(num) {
let fibSeries = [0, 1];
for (let i = 2; i <= num; i++) {
fibSeries.push(fibSeries[i - 1] + fibSeries[i - 2]);
}
return fibSeries;
}

// Function to check if a number is prime


function isPrime(num) {
if (num <= 1) return false;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
return false;
}
}
return true;
}

// Function to check if a number is palindrome


function isPalindrome(num) {
let strNum = num.toString();
let reversedNum = strNum.split('').reverse().join('');
return strNum === reversedNum;
}

// Function to display results of all operations


function performOperations() {
let num = parseInt(document.getElementById("number").value);

// Check if the input is a valid positive number


if (isNaN(num) || num <= 0) {
document.getElementById("result").innerHTML = "Please enter a valid positive
number.";
return;
}

let result = "";

// Factorial of the number


let fact = factorial(num);
result += `Factorial of ${num} is: ${fact}<br>`;

// Fibonacci series up to the number


let fibSeries = fibonacci(num);
result += `Fibonacci series up to ${num}: ${fibSeries.join(', ')}<br>`;

// Prime numbers up to the number


let primeNumbers = [];
for (let i = 1; i <= num; i++) {
if (isPrime(i)) {
primeNumbers.push(i);
}
}
result += `Prime numbers up to ${num}: ${primeNumbers.join(', ')}<br>`;

// Check if the number is palindrome


let palindromeResult = isPalindrome(num) ? `${num} is a Palindrome.` : `${num} is not
a Palindrome.`;
result += palindromeResult;

// Display the results in the div


document.getElementById("result").innerHTML = result;
}
</script>

</body>
</html>
2) Design a HTML having a text box and four buttons named Factorial,
Fibonacci, Prime,and Palindrome. When a button is pressed an appropriate
function should be called todisplay
i. Factorial of that number
ii. Fibonacci series up to that number
iii. Prime numbers up to that number
iv. Is it palindrome or not

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Number Operations</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
input {
padding: 5px;
margin-top: 10px;
width: 150px;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
margin: 10px;
}
div {
margin-top: 20px;
font-size: 18px;
margin-bottom: 10px;
word-wrap: break-word;
}
</style>
</head>
<body>

<h1>Number Operations</h1>

<label for="number">Enter a number:</label>


<input type="number" id="number" required><br><br>

<button onclick="calculateFactorial()">Factorial</button>
<button onclick="generateFibonacci()">Fibonacci</button>
<button onclick="findPrimeNumbers()">Prime Numbers</button>
<button onclick="checkPalindrome()">Palindrome</button>

<div id="result"></div>
<script>
// Function to calculate the factorial of a number
function calculateFactorial() {
let num = parseInt(document.getElementById("number").value);
if (isNaN(num) || num <= 0) {
document.getElementById("result").innerHTML = "Please enter a valid positive
number.";
return;
}
let result = 1;
for (let i = 1; i <= num; i++) {
result *= i;
}
document.getElementById("result").innerHTML = `Factorial of ${num} is: ${result}`;
}

// Function to generate the Fibonacci series up to a number


function generateFibonacci() {
let num = parseInt(document.getElementById("number").value);
if (isNaN(num) || num <= 0) {
document.getElementById("result").innerHTML = "Please enter a valid positive
number.";
return;
}
let fibSeries = [0, 1];
for (let i = 2; i <= num; i++) {
fibSeries.push(fibSeries[i - 1] + fibSeries[i - 2]);
}
document.getElementById("result").innerHTML = `Fibonacci series up to ${num}: $
{fibSeries.join(', ')}`;
}

// Function to find prime numbers up to a given number


function findPrimeNumbers() {
let num = parseInt(document.getElementById("number").value);
if (isNaN(num) || num <= 0) {
document.getElementById("result").innerHTML = "Please enter a valid positive
number.";
return;
}
let primeNumbers = [];
for (let i = 2; i <= num; i++) {
let isPrime = true;
for (let j = 2; j <= Math.sqrt(i); j++) {
if (i % j === 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primeNumbers.push(i);
}
}
document.getElementById("result").innerHTML = `Prime numbers up to ${num}: $
{primeNumbers.join(', ')}`;
}
// Function to check if the number is a palindrome
function checkPalindrome() {
let num = parseInt(document.getElementById("number").value);
if (isNaN(num) || num <= 0) {
document.getElementById("result").innerHTML = "Please enter a valid positive
number.";
return;
}
let strNum = num.toString();
let reversedNum = strNum.split('').reverse().join('');
if (strNum === reversedNum) {
document.getElementById("result").innerHTML = `${num} is a Palindrome.`;
} else {
document.getElementById("result").innerHTML = `${num} is not a Palindrome.`;
}
}
</script>

</body>
</html>
3)Write a program to validate the following fields in a registration page
i.Name (start with alphabet and followed by alphanumeric and the length
should
not be less than 6 characters)
ii. Mobile (only numbers and length 10 digits)
iii. E-mail (should contain format like [email protected])

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registration Form</title>
<style>
body {
font-family: Arial, sans-serif;
margin-top: 50px;
text-align: center;
}
form {
width: 300px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
background-color: #f9f9f9;
}
input {
width: 100%;
padding: 10px;
margin: 10px 0;
}
button {
width: 100%;
padding: 10px;
background-color: #4CAF50;
color: white;
font-size: 16px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
.error {
color: red;
font-size: 14px;
}
</style>
</head>
<body>

<h1>Registration Form</h1>
<form id="registrationForm" onsubmit="return validateForm()">
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your name">
<span class="error" id="nameError"></span>

<label for="mobile">Mobile Number:</label>


<input type="text" id="mobile" name="mobile" placeholder="Enter your mobile number">
<span class="error" id="mobileError"></span>

<label for="email">Email:</label>
<input type="email" id="email" name="email" placeholder="Enter your email">
<span class="error" id="emailError"></span>

<button type="submit">Register</button>
</form>

<script>
function validateForm() {
let valid = true;

// Clear previous error messages


document.getElementById("nameError").innerText = "";
document.getElementById("mobileError").innerText = "";
document.getElementById("emailError").innerText = "";
// Validate Name: Start with a letter, alphanumeric, and length >= 6
let name = document.getElementById("name").value;
let namePattern = /^[A-Za-z][A-Za-z0-9]{5,}$/;
if (!namePattern.test(name)) {
document.getElementById("nameError").innerText = "Name must start with a letter,
followed by alphanumeric characters, and be at least 6 characters long.";
valid = false;
}

// Validate Mobile Number: Only digits, length 10


let mobile = document.getElementById("mobile").value;
let mobilePattern = /^[0-9]{10}$/;
if (!mobilePattern.test(mobile)) {
document.getElementById("mobileError").innerText = "Mobile number must be
exactly 10 digits.";
valid = false;
}

// Validate Email: Format should be like [email protected]


let email = document.getElementById("email").value;
let emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (!emailPattern.test(email)) {
document.getElementById("emailError").innerText = "Please enter a valid email
address (e.g., [email protected]).";
valid = false; }
return valid;
}
</script></body></html>
Text Books:
1. Programming the World Wide Web, 7th Edition, Robet W Sebesta, Pearson, 2013.
2. Web Programming with HTML5, CSS and JavaScript, John Dean, Jones & Bartlett
Learning, 2019 (Chapters 1-11).
3. Pro MERN Stack: Full Stack Web App Development with Mongo, Express, React, and
Node, Vasan Subramanian, 2nd edition, APress, O’Reilly.

You might also like