1. Useof BasicTags
Basic HTML tags are the fundamental elements used to create a webpage. These include:
<!DOCTYPE html>: Declares the document type and version of HTML.
<html>: The root element that contains all other HTML elements.
<head>: Contains meta-information about the document, such as the title (<title>) and links to stylesheets.
<body>: Contains the content of the webpage, including text, images, and other media.
<h1> to <h6>: Headings, with <h1> being the highest (or most important) level.
<p>: Paragraph, used for blocks of text.
<a>: Anchor, used to create hyperlinks.
<img>: Image, used to embed images.
<ul>, <ol>, and <li>: Unordered and ordered lists, and list items.
<div>: Division, used to group block-level content.
<span>: Inline container, used to group inline content for styling or manipulation.
<!DOCTYPE html> <html> <head> <title>Text Formatting</title> </head> <body> <!-- Header for the page --> <h1>Text Formatting Examples</h1> <!-- Bold text --> <p><b>This text is bold.</b></p> <!-- Italic text --> <p><i>This text is italic.</i></p> <!-- Underlined text --> <p><u>This text is underlined.</u></p> <!-- Strikethrough text --> <p><strike>This text is strikethrough.</strike></p> <!-- Superscript text --> <p>This is <sup>superscript</sup> text.</p> <!-- Subscript text --> <p>This is <sub>subscript</sub> text.</p> <!-- Monospaced text --> <p><tt>This text is in monospaced font.</tt></p> </body> </html>
<!DOCTYPE html> <html> <head> <title>Font Tag and Colors</title> </head> <body> <!-- Header for the page --> <h1>Font Tag and Colors</h1> <!-- Using font tag with size, color, and face attributes --> <p><font size="4" color="blue" face="Arial">This is Arial text with size 4 and blue color.</font></p> <p><font size="5" color="green" face="Verdana">This is Verdana text with size 5 and green color.</font></p> <p><font size="3" color="red" face="Courier">This is Courier text with size 3 and red color.</font></p> <!-- Demonstrating various HTML color names --> <p style="color: crimson;">This text is in crimson color.</p> <p style="color: darkorange;">This text is in dark orange color.</p> <p style="color: mediumseagreen;">This text is in medium sea green color.</p> <p style="color: royalblue;">This text is in royal blue color.</p> <p style="color: darkviolet;">This text is in dark violet color.</p> </body> </html>
<!DOCTYPE html> <html> <head> <title>Navigation Page</title> </head> <body> <!-- Header for the page --> <h1>Web Page Navigation</h1> <!-- Navigation links to different pages --> <p><a href="page1.html">Go to Text Formatting Page</a></p> <p><a href="page2.html">Go to Font and Colors Page</a></p> <p><a href="page3.html">Refresh this Navigation Page</a></p> <!-- Footer for the page --> <footer> <p>© 2024 Example Website</p> </footer> </body> </html>
2. Navigation, list and paragraph.
Navigation: HTML provides <nav> tags to define navigation links. It groups a set of navigation links together, typically used for main site navigation.
List: HTML supports both ordered (<ol>) and unordered (<ul>) lists, which contain list items (<li>). Ordered lists use numbers, while unordered lists use bullets.
Paragraph: The <p> tag is used to define a paragraph of text. It provides space above and below the text and is used to organize content into readable sections.
<!DOCTYPE html>
<html>
<head>
<title>Text-Based Navigation Bar</title>
<style>
/* Style for the navigation bar */
.navbar {
overflow: hidden;
background-color: #333;
}
/* Style for navigation links */
.navbar a {
float: left;
display: block;
color: white;
text-align: center;
padding: 14px 20px;
text-decoration: none;
}
/* Change color on hover */
.navbar a:hover {
background-color: #ddd;
color: black;
}
</style>
</head>
<body>
<!-- Navigation bar -->
<div class="navbar">
<a href="page1.html">Home</a>
<a href="page2.html">Lists & Backgrounds</a>
<a href="page3.html">Paragraphs</a>
</div>
<!-- Header for the page -->
<h1>Welcome to the Text-Based Navigation Bar Page</h1>
<p>This page demonstrates a simple text-based navigation bar.</p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Lists and Backgrounds</title>
<style>
/* Set a background image for the body */
body {
background-image: url('background.jpg');
background-size: cover;
color: white;
}
/* Style for the lists */
ul, ol {
background: rgba(0, 0, 0, 0.5);
padding: 20px;
border-radius: 10px;
}
</style>
</head>
<body>
<!-- Header for the page -->
<h1>Lists and Backgrounds</h1>
<!-- Unordered list example -->
<h2>Unordered List</h2>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<!-- Ordered list example -->
<h2>Ordered List</h2>
<ol>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ol>
<!-- Navigation link back to Home -->
<p><a href="page1.html">Back to Home</a></p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Paragraphs and Associated Tags</title>
</head>
<body>
<!-- Header for the page -->
<h1>Paragraphs and Associated Tags</h1>
<!-- Demonstrating paragraph tags -->
<p>This is a paragraph of text. Paragraphs are block-level elements and are always displayed on new lines.</p>
<!-- Using line break tag -->
<p>This is a line of text.<br>This is another line of text on a new line using the <code><br></code> tag.</p>
<!-- Using preformatted text tag -->
<pre>
This is preformatted text.
It preserves both spaces and
line breaks.
</pre>
<!-- Blockquote tag -->
<blockquote>
This is a blockquote. It is used to denote a section that is quoted from another source.
</blockquote>
<!-- Navigation link back to Home -->
<p><a href="page1.html">Back to Home</a></p>
</body>
</html>
3. Lists, Images and Semantics:
Lists: Lists are used to present information in a structured manner. Unordered lists (<ul>) display bullet points, while ordered lists (<ol>) display numbered items. Description lists (<dl>) pair terms with descriptions.
Images: The <img> tag embeds images in a webpage. Attributes like src (source), alt (alternative text), width, and height provide details about the image.
Semantics: Semantic HTML elements, like <article>, <section>, <header>, <footer>, and <aside>, give meaning to the structure of a webpage, improving accessibility and SEO by clearly defining different parts of the content.
<!DOCTYPE html> <html> <head> <title>Multiple Images</title> </head> <body> <!-- Header for the page --> <h1>Multiple Images Example</h1> <!-- Adding multiple images --> <img src="image1.jpg" alt="Image 1" width="300" height="200"> <img src="image2.jpg" alt="Image 2" width="300" height="200"> <img src="image3.jpg" alt="Image 3" width="300" height="200"> <!-- Adding images with different alignments --> <p><img src="image4.jpg" alt="Image 4" width="150" height="100" align="left">This text is aligned to the right of the image.</p> <p><img src="image5.jpg" alt="Image 5" width="150" height="100" align="right">This text is aligned to the left of the image.</p> <!-- Footer for the page --> <footer> <p><a href="page2.html">Go to Image Maps Page</a></p> <p><a href="page3.html">Go to Semantic Tags Page</a></p> </footer> </body> </html>
<!DOCTYPE html> <html> <head> <title>Image Maps</title> </head> <body> <!-- Header for the page --> <h1>Image Maps Example</h1> <!-- Adding an image map --> <img src="world_map.jpg" alt="World Map" usemap="#worldmap" width="600" height="400"> <!-- Defining the map with clickable areas --> <map name="worldmap"> <area shape="rect" coords="34,44,270,350" alt="Africa" href="https://en.wikipedia.org/wiki/Africa"> <area shape="circle" coords="477,300,44" alt="Australia" href="https://en.wikipedia.org/wiki/Australia"> <area shape="poly" coords="130,136,180,136,180,184,140,210,110,180" alt="South America" href="https://en.wikipedia.org/wiki/South_America"> </map> <!-- Footer for the page --> <footer> <p><a href="page1.html">Back to Multiple Images Page</a></p> <p><a href="page3.html">Go to Semantic Tags Page</a></p> </footer> </body> </html>
<!DOCTYPE html>
<html>
<head>
<title>Semantic Tags</title>
</head>
<body>
<!-- Header for the page -->
<header>
<h1>Semantic Tags Example</h1>
<nav>
<ul>
<li><a href="page1.html">Multiple Images</a></li>
<li><a href="page2.html">Image Maps</a></li>
<li><a href="page3.html">Semantic Tags</a></li>
</ul>
</nav>
</header>
<!-- Main content area -->
<main>
<article>
<h2>Article Title</h2>
<p>This is an article section. Articles are used to encapsulate a piece of content that can stand alone.</p>
</article>
<section>
<h2>Section Title</h2>
<p>This is a section within the main content. Sections are used to group related content together.</p>
</section>
<aside>
<h2>Aside Title</h2>
<p>This is an aside section. Asides are used for content that is tangentially related to the main content.</p>
</aside>
</main>
<!-- Footer for the page -->
<footer>
<p>© 2024 Example Website</p>
</footer>
</body>
</html>
4. Multimedia and User controls:
Multimedia: HTML supports embedding multimedia elements like audio (<audio>) and video (<video>). These tags include controls for play, pause, and volume.
User Controls: HTML forms (<form>) include various input elements for user interaction:
Text fields (<input type="text">)
Password fields (<input type="password">)
Radio buttons (<input type="radio">)
Checkboxes (<input type="checkbox">)
Dropdown lists (<select>)
Buttons (<button>, <input type="submit">)
<!DOCTYPE html>
<html>
<head>
<title>Form with User Controls</title>
</head>
<body>
<!-- Header for the page -->
<h1>User Controls Form</h1>
<!-- Form demonstrating various user controls -->
<form action="/submit_form" method="post">
<!-- Text input -->
<label for="fname">First Name:</label><br>
<input type="text" id="fname" name="fname"><br><br>
<!-- Password input -->
<label for="pwd">Password:</label><br>
<input type="password" id="pwd" name="pwd"><br><br>
<!-- Radio buttons -->
<label>Gender:</label><br>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br><br>
<!-- Checkboxes -->
<label>Skills:</label><br>
<input type="checkbox" id="skill1" name="skills" value="HTML">
<label for="skill1"> HTML</label><br>
<input type="checkbox" id="skill2" name="skills" value="CSS">
<label for="skill2"> CSS</label><br>
<input type="checkbox" id="skill3" name="skills" value="JavaScript">
<label for="skill3"> JavaScript</label><br><br>
<!-- Dropdown menu -->
<label for="country">Country:</label><br>
<select id="country" name="country">
<option value="usa">USA</option>
<option value="canada">Canada</option>
<option value="uk">UK</option>
</select><br><br>
<!-- Textarea -->
<label for="bio">Biography:</label><br>
<textarea id="bio" name="bio" rows="4" cols="50"></textarea><br><br>
<!-- Date input -->
<label for="dob">Date of Birth:</label><br>
<input type="date" id="dob" name="dob"><br><br>
<!-- Color input -->
<label for="favcolor">Favorite Color:</label><br>
<input type="color" id="favcolor" name="favcolor"><br><br>
<!-- File upload -->
<label for="resume">Upload Resume:</label><br>
<input type="file" id="resume" name="resume"><br><br>
<!-- Range input -->
<label for="experience">Experience (years):</label><br>
<input type="range" id="experience" name="experience" min="0" max="30"><br><br>
<!-- Submit button -->
<input type="submit" value="Submit">
</form>
<!-- Footer for the page -->
<footer>
<p><a href="page2.html">Go to Multimedia Page</a></p>
<p><a href="page3.html">Go to Static Website</a></p>
</footer>
</body>
</html>
<!DOCTYPE html> <html> <head> <title>Multimedia Features</title> </head> <body> <!-- Header for the page --> <h1>Embedding Multimedia Features</h1> <!-- Embedding an image --> <h2>Image</h2> <img src="example.jpg" alt="Example Image" width="500" height="300"> <!-- Embedding a video --> <h2>Video</h2> <video width="500" height="300" controls> <source src="example.mp4" type="video/mp4"> Your browser does not support the video tag. </video> <!-- Embedding an audio --> <h2>Audio</h2> <audio controls> <source src="example.mp3" type="audio/mpeg"> Your browser does not support the audio element. </audio> <!-- Embedding a YouTube video --> <h2>YouTube Video</h2> <iframe width="500" height="300" src="https://www.youtube.com/embed/example" frameborder="0" allowfullscreen></iframe> <!-- Footer for the page --> <footer> <p><a href="page1.html">Back to User Controls Form</a></p> <p><a href="page3.html">Go to Static Website</a></p> </footer> </body> </html>
<!--page1.html-->
<!DOCTYPE html>
<html>
<head>
<title>Static Website - Home</title>
</head>
<body>
<!-- Header for the page -->
<header>
<h1>Welcome to Our Static Website</h1>
<nav>
<ul>
<li><a href="home.html">Home</a></li>
<li><a href="about.html">About</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</nav>
</header>
<!-- Main content area -->
<main>
<section>
<h2>Introduction</h2>
<p>This is the home page of our static website. Explore the other pages to learn more about us.</p>
</section>
</main>
<!-- Footer for the page -->
<footer>
<p>© 2024 Example Static Website</p>
</footer>
</body>
</html>
<!--page2.html-->
<!DOCTYPE html>
<html>
<head>
<title>Static Website - About</title>
</head>
<body>
<!-- Header for the page -->
<header>
<h1>About Us</h1>
<nav>
<ul>
<li><a href="home.html">Home</a></li>
<li><a href="about.html">About</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</nav>
</header>
<!-- Main content area -->
<main>
<section>
<h2>Our Mission</h2>
<p>Our mission is to provide the best services to our customers.</p>
</section>
<section>
<h2>Our Team</h2>
<p>We have a dedicated team of professionals.</p>
</section>
</main>
<!-- Footer for the page -->
<footer>
<p>© 2024 Example Static Website</p>
</footer>
</body>
</html>
<!--page3.html-->
<!DOCTYPE html>
<html>
<head>
<title>Static Website - Contact</title>
</head>
<body>
<!-- Header for the page -->
<header>
<h1>Contact Us</h1>
<nav>
<ul>
<li><a href="home.html">Home</a></li>
<li><a href="about.html">About</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</nav>
</header>
<!-- Main content area -->
<main>
<section>
<h2>Get in Touch</h2>
<p>Email us at <a href="mailto:info@example.com">info@example.com</a></p>
</section>
</main>
<!-- Footer for the page -->
<footer>
<p>© 2024 Example Static Website</p>
</footer>
</body>
</html>
5. CSS with list, links and table:
Lists: CSS styles lists by changing bullet styles, indentation, and spacing. Use list-style-type, margin, and padding properties.
Links: CSS can style links (<a>) with pseudo-classes like :link, :visited, :hover, and :active to change color, underline, and other properties.
Table: CSS styles tables (<table>) to enhance readability. Use border, padding, text-align, background-color, and border-collapse properties for styling.
<!DOCTYPE html>
<html>
<head>
<title>Styled Lists</title>
<style>
/* Style for unordered list */
ul.styled-list {
list-style-type: square;
color: blue;
}
/* Style for ordered list */
ol.styled-list {
list-style-type: upper-roman;
color: green;
}
/* Style for nested list */
ul.nested-list li {
margin-bottom: 5px;
}
ul.nested-list ul {
list-style-type: circle;
color: red;
margin-left: 20px;
}
</style>
</head>
<body>
<!-- Header for the page -->
<h1>Different Types of Styled Lists</h1>
<!-- Unordered list -->
<h2>Unordered List</h2>
<ul class="styled-list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<!-- Ordered list -->
<h2>Ordered List</h2>
<ol class="styled-list">
<li>First</li>
<li>Second</li>
<li>Third</li>
</ol>
<!-- Nested list -->
<h2>Nested List</h2>
<ul class="nested-list">
<li>Parent Item 1
<ul>
<li>Child Item 1</li>
<li>Child Item 2</li>
</ul>
</li>
<li>Parent Item 2</li>
</ul>
<!-- Footer for the page -->
<footer>
<p><a href="page2.html">Go to Hyperlinks Page</a></p>
<p><a href="page3.html">Go to Tables Page</a></p>
</footer>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Styled Hyperlinks</title>
<style>
/* Default link style */
a {
text-decoration: none;
color: black;
}
/* Visited link */
a:visited {
color: purple;
}
/* Hovered link */
a:hover {
text-decoration: underline;
color: red;
}
/* Active link */
a:active {
color: orange;
}
/* Style for a specific class of links */
a.special-link {
font-weight: bold;
color: blue;
}
</style>
</head>
<body>
<!-- Header for the page -->
<h1>Styled Hyperlinks</h1>
<!-- Different states of links -->
<p><a href="https://www.example.com" target="_blank">Default Link</a></p>
<p><a href="https://www.example.com" target="_blank" class="special-link">Special Link</a></p>
<!-- Footer for the page -->
<footer>
<p><a href="page1.html">Back to Lists Page</a></p>
<p><a href="page3.html">Go to Tables Page</a></p>
</footer>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Styled Tables</title>
<style>
/* Style for table */
table.styled-table {
width: 100%;
border-collapse: collapse;
}
/* Style for table headers */
table.styled-table th {
background-color: #f2f2f2;
color: black;
padding: 10px;
}
/* Style for table data cells */
table.styled-table td {
padding: 10px;
text-align: center;
border: 1px solid #ddd;
}
/* Style for table rows */
table.styled-table tr:nth-child(even) {
background-color: #f9f9f9;
}
table.styled-table tr:hover {
background-color: #f1f1f1;
}
</style>
</head>
<body>
<!-- Header for the page -->
<h1>Styled Tables</h1>
<!-- Table demonstrating various styles -->
<table class="styled-table">
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1, Cell 1</td>
<td>Row 1, Cell 2</td>
<td>Row 1, Cell 3</td>
</tr>
<tr>
<td>Row 2, Cell 1</td>
<td>Row 2, Cell 2</td>
<td>Row 2, Cell 3</td>
</tr>
<tr>
<td>Row 3, Cell 1</td>
<td>Row 3, Cell 2</td>
<td>Row 3, Cell 3</td>
</tr>
</tbody>
</table>
<!-- Footer for the page -->
<footer>
<p><a href="page1.html">Back to Lists Page</a></p>
<p><a href="page2.html">Back to Hyperlinks Page</a></p>
</footer>
</body>
</html>
6. CSS with font, paragraph and types:
Font: CSS properties like font-family, font-size, font-weight, and color are used to style text.
Paragraph: CSS properties such as text-align, line-height, margin, and padding enhance paragraph presentation.
Types: CSS can be applied using inline styles, internal stylesheets, or external stylesheets. Inline styles use the style attribute within HTML elements. Internal styles are defined within a <style> tag in the <head>. External styles link to a separate CSS file using the <link> tag.
<!DOCTYPE html>
<html>
<head>
<title>Styled Fonts</title>
<style>
/* Style for heading fonts */
h1, h2 {
font-family: 'Arial', sans-serif;
color: darkblue;
}
/* Style for paragraph fonts */
p {
font-family: 'Georgia', serif;
color: darkgreen;
}
/* Style for a specific class */
.special-font {
font-family: 'Courier New', monospace;
color: darkred;
font-size: larger;
text-decoration: underline;
}
</style>
</head>
<body>
<!-- Header for the page -->
<h1>Styled Fonts Example</h1>
<!-- Subheading with styled font -->
<h2>Subheading</h2>
<!-- Paragraph with default styled font -->
<p>This is a paragraph with Georgia font and dark green color.</p>
<!-- Paragraph with special font class -->
<p class="special-font">This paragraph has a special font style.</p>
<!-- Footer for the page -->
<footer>
<p><a href="page2.html">Go to Paragraph Styles Page</a></p>
<p><a href="page3.html">Go to CSS Demonstration Page</a></p>
</footer>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Styled Paragraphs</title>
<style>
/* Style for all paragraphs */
p {
color: darkslategray;
line-height: 1.6;
margin: 20px 0;
}
/* Style for paragraphs with a specific class */
p.highlight {
background-color: lightyellow;
border-left: 5px solid gold;
padding-left: 10px;
}
/* Style for paragraphs with another specific class */
p.italic {
font-style: italic;
}
</style>
</head>
<body>
<!-- Header for the page -->
<h1>Styled Paragraphs Example</h1>
<!-- Paragraph with default style -->
<p>This is a standard paragraph styled with a specific color and line height.</p>
<!-- Paragraph with highlight class -->
<p class="highlight">This paragraph is highlighted with a background color and border.</p>
<!-- Paragraph with italic class -->
<p class="italic">This paragraph is styled with italic text.</p>
<!-- Paragraph with both classes -->
<p class="highlight italic">This paragraph combines both the highlight and italic styles.</p>
<!-- Footer for the page -->
<footer>
<p><a href="page1.html">Back to Font Styles Page</a></p>
<p><a href="page3.html">Go to CSS Demonstration Page</a></p>
</footer>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>CSS Demonstration</title>
<!-- Internal CSS -->
<style>
body {
font-family: Arial, sans-serif;
}
h1 {
color: navy;
text-align: center;
}
p {
color: darkgray;
font-size: 18px;
margin: 20px;
}
/* Style for a class */
.highlight {
background-color: lightblue;
padding: 10px;
border-radius: 5px;
}
</style>
<!-- Linking to an external CSS file -->
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<!-- Header for the page -->
<h1>CSS Demonstration</h1>
<!-- Paragraph styled with internal CSS -->
<p>This paragraph is styled with internal CSS. It has a dark gray color and a margin.</p>
<!-- Paragraph styled with both internal and external CSS -->
<p class="highlight">This paragraph is styled with both internal and external CSS. It has a light blue background and rounded borders.</p>
<!-- Paragraph with inline CSS -->
<p style="color: darkred; font-size: 20px;">This paragraph is styled with inline CSS. It has a dark red color and larger font size.</p>
<!-- Footer for the page -->
<footer>
<p><a href="page1.html">Back to Font Styles Page</a></p>
<p><a href="page2.html">Back to Paragraph Styles Page</a></p>
</footer>
</body>
</html>
<mark><!-- External CSS file for Page 3 --></mark>
/* External CSS file for Page 3 */
/* Style for all paragraphs */
p {
font-family: 'Verdana', sans-serif;
line-height: 1.5;
margin: 15px;
color: darkolivegreen;
}
/* Additional styles for the highlight class */
.highlight {
border: 2px solid blue;
}
7. JavaScript: Validating User fields.
JavaScript validates user input in forms to ensure data integrity before submission. Validation checks include:
Required Fields: Ensuring fields are not empty.
Format Checks: Validating email addresses with regex.
Password Matching: Ensuring password and confirm password fields match.
Field Length: Checking the length of input fields.
JavaScript validation functions typically run on form submission (onsubmit) and can display error messages using alert or by manipulating the DOM.
<!DOCTYPE html>
<html>
<head>
<title>Document Object Methods</title>
<script>
// Function to demonstrate document object methods
function manipulateDOM() {
// Change the content of an element by ID
document.getElementById("demo").innerHTML = "Content changed using document.getElementById()!";
// Change the background color of all elements with the class name "example"
var elements = document.getElementsByClassName("example");
for (var i = 0; i < elements.length; i++) {
elements[i].style.backgroundColor = "lightblue";
}
// Change the font size of all paragraphs
var paragraphs = document.getElementsByTagName("p");
for (var j = 0; j < paragraphs.length; j++) {
paragraphs[j].style.fontSize = "20px";
}
}
</script>
</head>
<body>
<h1>Document Object Methods Example</h1>
<!-- Paragraph with ID to be changed by JavaScript -->
<p id="demo">This is a paragraph that will be changed.</p>
<!-- Paragraphs with class name to change background color -->
<p class="example">Example paragraph 1.</p>
<p class="example">Example paragraph 2.</p>
<!-- Button to trigger JavaScript function -->
<button onclick="manipulateDOM()">Change Content and Style</button>
<!-- Footer for navigation -->
<footer>
<p><a href="page2.html">Go to Validation Page 1</a></p>
<p><a href="page3.html">Go to Validation Page 2</a></p>
</footer>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Form Validation Page 1</title>
<script>
// Function to validate form fields
function validateForm() {
// Validate text input
var name = document.forms["myForm"]["name"].value;
if (name == "") {
alert("Name must be filled out");
return false;
}
// Validate dropdown list
var country = document.forms["myForm"]["country"].value;
if (country == "") {
alert("Please select a country");
return false;
}
// Validate checkboxes
var terms = document.forms["myForm"]["terms"].checked;
if (!terms) {
alert("You must accept the terms and conditions");
return false;
}
alert("Form submitted successfully!");
return true;
}
</script>
</head>
<body>
<h1>Form Validation Example</h1>
<!-- Form to be validated -->
<form name="myForm" onsubmit="return validateForm()">
<!-- Text input field -->
Name: <input type="text" name="name"><br><br>
<!-- Dropdown list -->
Country:
<select name="country">
<option value="">Select</option>
<option value="USA">USA</option>
<option value="Canada">Canada</option>
<option value="UK">UK</option>
</select><br><br>
<!-- Checkbox -->>
<input type="checkbox" name="terms"> I accept the terms and conditions><br><br>
<!-- Submit button -->
<input type="submit" value="Submit">
</form>
<!-- Footer for navigation -->
<footer>
<p><a href="page1.html">Back to Document Object Methods</a></p>
<p><a href="page3.html">Go to Validation Page 2</a></p>
</footer>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Form Validation Page 2</title>
<script>
// Function to validate radio buttons and multi-select boxes
function validateForm() {
// Validate radio buttons
var gender = document.forms["myForm"]["gender"];
var genderSelected = false;
for (var i = 0; i < gender.length; i++) {
if (gender[i].checked) {
genderSelected = true;
break;
}
}
if (!genderSelected) {
alert("Please select your gender");
return false;
}
// Validate multi-select boxes
var interests = document.forms["myForm"]["interests"];
var selectedInterests = [];
for (var j = 0; j < interests.length; j++) {
if (interests[j].selected) {
selectedInterests.push(interests[j].value);
}
}
if (selectedInterests.length == 0) {
alert("Please select at least one interest");
return false;
}
alert("Form submitted successfully!");
return true;
}
</script>
</head>
<body>
<h1>Form Validation Example</h1>
<!-- Form to be validated -->
<form name="myForm" onsubmit="return validateForm()">
<!-- Radio buttons -->
Gender:
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female<br><br>
<!-- Multi-select box -->
Interests:
<select name="interests" multiple>
<option value="music">Music</option>
<option value="sports">Sports</option>
<option value="reading">Reading</option>
<option value="travelling">Travelling</option>
</select><br><br>
<!-- Submit button -->
<input type="submit" value="Submit">
</form>
<!-- Footer for navigation -->
<footer>
<p><a href="page1.html">Back to Document Object Methods</a></p>
<p><a href="page2.html">Back to Validation Page 1</a></p>
</footer>
</body>
</html>
8. JavaScript :Handling the events.
JavaScript interacts with various user events to create dynamic webpages:
onAbort: Triggered when media loading is aborted.
onBlur: Triggered when an element loses focus.
onChange: Triggered when the value of an input changes.
onClick: Triggered when an element is clicked.
onDblClick: Triggered on double-click.
onDragDrop: Triggered during drag-and-drop actions.
onError: Triggered when an error occurs.
onFocus: Triggered when an element gains focus.
onMouseDown: Triggered when a mouse button is pressed.
onMouseMove: Triggered when the mouse is moved.
onMouseOut: Triggered when the mouse leaves an element.
onMouseOver: Triggered when the mouse hovers over an element.
onMouseUp: Triggered when a mouse button is released.
onKeyDown: Triggered when a key is pressed.
onKeyPress: Triggered when a key is pressed and held.
onKeyUp: Triggered when a key is released.
onLoad: Triggered when the document has loaded.
onResize: Triggered when the window is resized.
onSelect: Triggered when text is selected.
onSubmit: Triggered when a form is submitted.
onUnload: Triggered when the document is unloaded.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Events Page 1</title>
<script>
// Function to handle onAbort event
function onAbortHandler() {
alert("Media load was aborted!");
}
// Function to handle onBlur event
function onBlurHandler() {
alert("Input field lost focus!");
}
// Function to handle onChange event
function onChangeHandler() {
alert("Dropdown selection changed!");
}
// Function to handle onClick event
function onClickHandler() {
alert("Button clicked!");
}
// Function to handle onDblClick event
function onDblClickHandler() {
alert("Button double-clicked!");
}
</script>
</head>
<body>
<h1>JavaScript Events Example 1</h1>
<!-- Image to demonstrate onAbort event -->
<img src="invalid-url.jpg" onabort="onAbortHandler()" alt="Invalid Image">
<!-- Input field to demonstrate onBlur event -->
<input type="text" onblur="onBlurHandler()" placeholder="Click here and then click outside">
<!-- Dropdown to demonstrate onChange event -->
<select onchange="onChangeHandler()">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
<!-- Button to demonstrate onClick event -->
<button onclick="onClickHandler()">Click Me!</button>
<!-- Button to demonstrate onDblClick event -->
<button ondblclick="onDblClickHandler()">Double Click Me!</button>
<!-- Footer for navigation -->
<footer>
<p><a href="page2.html">Go to Page 2</a></p>
</footer>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Events Page 2</title>
<script>
// Function to handle onDrag event
function onDragHandler(event) {
event.dataTransfer.setData("text", event.target.id);
}
// Function to handle onDrop event
function onDropHandler(event) {
event.preventDefault();
var data = event.dataTransfer.getData("text");
event.target.appendChild(document.getElementById(data));
}
// Function to handle onDragOver event
function onDragOverHandler(event) {
event.preventDefault();
}
// Function to handle onError event
function onErrorHandler() {
alert("An error occurred while loading the image!");
}
// Function to handle onFocus event
function onFocusHandler() {
alert("Input field gained focus!");
}
</script>
</head>
<body>
<h1>JavaScript Events Example 2</h1>
<!-- Image to demonstrate onError event -->
<img src="invalid-url.jpg" onerror="onErrorHandler()" alt="Invalid Image">
<!-- Input field to demonstrate onFocus event -->
<input type="text" onfocus="onFocusHandler()" placeholder="Click here to gain focus">
<!-- Div elements to demonstrate onDrag, onDrop, and onDragOver events -->
<div id="drag1" draggable="true" ondragstart="onDragHandler(event)" style="width: 100px; height: 100px; background-color: lightblue; margin: 10px;">Drag me</div>
<div ondrop="onDropHandler(event)" ondragover="onDragOverHandler(event)" style="width: 200px; height: 200px; background-color: lightgray; margin: 10px;">Drop here</div>
<!-- Footer for navigation -->
<footer>
<p><a href="page1.html">Back to Page 1</a></p>
<p><a href="page3.html">Go to Page 3</a></p>
</footer>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Events Page 3</title>
<script>
// Function to handle onMouseDown event
function onMouseDownHandler() {
document.getElementById("mouse-event").innerHTML = "Mouse button pressed!";
}
// Function to handle onMouseMove event
function onMouseMoveHandler(event) {
document.getElementById("mouse-event").innerHTML = "Mouse moved at (" + event.clientX + ", " + event.clientY + ")";
}
// Function to handle onMouseOut event
function onMouseOutHandler() {
document.getElementById("mouse-event").innerHTML = "Mouse left the element!";
}
// Function to handle onMouseOver event
function onMouseOverHandler() {
document.getElementById("mouse-event").innerHTML = "Mouse over the element!";
}
// Function to handle onMouseUp event
function onMouseUpHandler() {
document.getElementById("mouse-event").innerHTML = "Mouse button released!";
}
</script>
</head>
<body>
<h1>JavaScript Events Example 3</h1>
<!-- Div to demonstrate mouse events -->
<div id="mouse-event" onmousedown="onMouseDownHandler()" onmousemove="onMouseMoveHandler(event)" onmouseout="onMouseOutHandler()" onmouseover="onMouseOverHandler()" onmouseup="onMouseUpHandler()" style="width: 200px; height: 200px; background-color: lightgray; margin: 10px;">Interact with me</div>
<!-- Footer for navigation -->
<footer>
<p><a href="page2.html">Back to Page 2</a></p>
<p><a href="page4.html">Go to Page 4</a></p>
</footer>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Events Page 4</title>
<script>
// Function to handle onLoad event
function onLoadHandler() {
alert("Page loaded successfully!");
}
// Function to handle onUnload event
function onUnloadHandler() {
alert("You are leaving the page!");
}
// Function to handle onKeyDown event
function onKeyDownHandler(event) {
document.getElementById("key-event").innerHTML = "Key down: " + event.key;
}
// Function to handle onKeyPress event
function onKeyPressHandler(event) {
document.getElementById("key-event").innerHTML = "Key press: " + event.key;
}
// Function to handle onKeyUp event
function onKeyUpHandler(event) {
document.getElementById("key-event").innerHTML = "Key up: " + event.key;
}
// Function to handle onReset event
function onResetHandler() {
alert("Form has been reset!");
}
// Function to handle onResize event
function onResizeHandler() {
document.getElementById("resize-event").innerHTML = "Window resized to (" + window.innerWidth + ", " + window.innerHeight + ")";
}
// Function to handle onSelect event
function onSelectHandler() {
alert("Text has been selected!");
}
// Function to handle onSubmit event
function onSubmitHandler() {
alert("Form submitted successfully!");
return false;
}
</script>
</head>
<body onload="onLoadHandler()" onunload="onUnloadHandler()" onresize="onResizeHandler()">
<h1>JavaScript Events Example 4</h1>
<!-- Input field to demonstrate key events -->
<input type="text" id="key-event" onkeydown="onKeyDownHandler(event)" onkeypress="onKeyPressHandler(event)" onkeyup="onKeyUpHandler(event)" placeholder="Type something">
<!-- Text area to demonstrate onSelect event -->
<textarea onselect="onSelectHandler()" placeholder="Select some text"></textarea>
<!-- Form to demonstrate onReset and onSubmit events -->
<form onsubmit="return onSubmitHandler()" onreset="onResetHandler()">
<input type="text" placeholder="Enter something">
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
<!-- Footer for navigation -->
<footer>
<p><a href="page3.html">Back to Page 3</a></p>
<p><a href="page5.html">Go to Page 5</a></p>
</footer>
<!-- Div to display window resize event -->
<div id="resize-event" style="margin-top: 20px;">Resize the window to see the effect.</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>User Registration Form</title>
<script>
// Function to validate the registration form
function validateForm() {
// Validate name
var name = document.forms["registrationForm"]["name"].value;
if (name == "") {
alert("Name must be filled out");
return false;
}
// Validate email
var email = document.forms["registrationForm"]["email"].value;
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
if (!emailPattern.test(email)) {
alert("Invalid email address");
return false;
}
// Validate password
var password = document.forms["registrationForm"]["password"].value;
if (password == "") {
alert("Password must be filled out");
return false;
}
// Validate confirm password
var confirmPassword = document.forms["registrationForm"]["confirmPassword"].value;
if (password !== confirmPassword) {
alert("Passwords do not match");
return false;
}
// Validate gender
var gender = document.forms["registrationForm"]["gender"].value;
if (gender == "") {
alert("Gender must be selected");
return false;
}
// Validate hobbies
var hobbies = document.forms["registrationForm"]["hobbies"];
var hobbiesSelected = false;
for (var i = 0; i < hobbies.length; i++) {
if (hobbies[i].checked) {
hobbiesSelected = true;
break;
}
}
if (!hobbiesSelected) {
alert("At least one hobby must be selected");
return false;
}
// Validate country
var country = document.forms["registrationForm"]["country"].value;
if (country == "") {
alert("Country must be selected");
return false;
}
// All validations passed
alert("Form submitted successfully!");
return true;
}
</script>
</head>
<body>
<h1>User Registration Form</h1>
<!-- User Registration Form -->
<form name="registrationForm" onsubmit="return validateForm()">
<!-- Name -->
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<!-- Email -->
<label for="email">Email:</label>
<input type="text" id="email" name="email"><br><br>
<!-- Password -->
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>
<!-- Confirm Password -->
<label for="confirmPassword">Confirm Password:</label>
<input type="password" id="confirmPassword" name="confirmPassword"><br><br>
<!-- Gender -->
<label for="gender">Gender:</label>
<input type="radio" id="male" name="gender" value="male"> Male
<input type="radio" id="female" name="gender" value="female"> Female
<input type="radio" id="other" name="gender" value="other"> Other<br><br>
<!-- Hobbies -->
<label for="hobbies">Hobbies:</label>
<input type="checkbox" id="hobby1" name="hobbies" value="Reading"> Reading
<input type="checkbox" id="hobby2" name="hobbies" value="Traveling"> Traveling
<input type="checkbox" id="hobby3" name="hobbies" value="Cooking"> Cooking<br><br>
<!-- Country -->
<label for="country">Country:</label>
<select id="country" name="country">
<option value="">Select Country</option>
<option value="USA">USA</option>
<option value="Canada">Canada</option>
<option value="UK">UK</option>
<option value="Australia">Australia</option>
</select><br><br>
<!-- Submit Button -->
<input type="submit" value="Register">
</form>
<!-- Footer for navigation -->
<footer>
<p><a href="page4.html">Back to Page 4</a></p>
</footer>
</body>
</html>
9. JSON Basic.
JSON (JavaScript Object Notation) is a lightweight data interchange format.
It is easy to read and write for humans and easy for machines to parse and generate.
JSON represents data as key-value pairs within curly braces {}.
Arrays are denoted by square brackets [].
It is language-independent and widely used for data exchange between a server and web application.
<!DOCTYPE html>
<html>
<head>
<title>Create JSON</title>
<script>
// Function to create JSON object
function createJSON() {
var student = {
"name": "John Doe",
"age": 20,
"course": "Computer Science",
"grades": {
"math": 95,
"science": 88,
"history": 75
}
};
// Convert JSON object to string
var jsonString = JSON.stringify(student);
// Display JSON string
alert(jsonString);
}
</script>
</head>
<body>
<h1>Create JSON Example</h1>
<!-- Button to trigger JSON creation -->
<button onclick="createJSON()">Create JSON</button>
<!-- Footer for navigation -->
<footer>
<p><a href="page2.html">Go to Page 2</a></p>
</footer>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Parse JSON</title>
<script>
// Function to parse JSON string
function parseJSON() {
var jsonString = '{"name":"Jane Smith","age":22,"course":"Physics","grades":{"math":90,"science":85,"history":78}}';
// Convert JSON string to object
var student = JSON.parse(jsonString);
// Display parsed JSON object
alert("Name: " + student.name + "\nAge: " + student.age + "\nCourse: " + student.course);
}
</script>
</head>
<body>
<h1>Parse JSON Example</h1>
<!-- Button to trigger JSON parsing -->
<button onclick="parseJSON()">Parse JSON</button>
<!-- Footer for navigation -->
<footer>
<p><a href="page1.html">Back to Page 1</a></p>
<p><a href="page3.html">Go to Page 3</a></p>
</footer>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Persist JSON</title>
<script>
// Function to persist JSON object
function persistJSON() {
var student = {
"name": "Alice Johnson",
"age": 25,
"course": "Biology",
"grades": {
"math": 85,
"science": 92,
"history": 80
}
};
// Convert JSON object to string
var jsonString = JSON.stringify(student);
// Store JSON string in local storage
localStorage.setItem("studentData", jsonString);
alert("JSON data persisted successfully!");
}
</script>
</head>
<body>
<h1>Persist JSON Example</h1>
<!-- Button to trigger JSON persistence -->
<button onclick="persistJSON()">Persist JSON</button>
<!-- Footer for navigation -->
<footer>
<p><a href="page2.html">Back to Page 2</a></p>
</footer>
</body>
</html>
10. Working with JSON.
Working with JSON involves creating, parsing, and manipulating JSON data in JavaScript:
Creating JSON: Define a JSON object or array and use JSON.stringify() to convert it into a JSON string.
Parsing JSON: Use JSON.parse() to convert a JSON string into a JavaScript object.
Persisting JSON: Store JSON data in local storage or send it to a server for persistence.
<!DOCTYPE html>
<html>
<head>
<title>JSON Objects in Array</title>
</head>
<body>
<h1>JSON Objects in Array</h1>
<!-- Script to define JSON array and print it on the webpage -->
<script>
var students = [
{
"name": "John Doe",
"age": 20,
"course": "Computer Science"
},
{
"name": "Jane Smith",
"age": 22,
"course": "Physics"
},
{
"name": "Alice Johnson",
"age": 25,
"course": "Biology"
}
];
// Function to print JSON array on the webpage
function printStudents() {
var output = "<ul>";
students.forEach(function(student) {
output += "<li>Name: " + student.name + ", Age: " + student.age + ", Course: " + student.course + "</li>";
});
output += "</ul>";
document.getElementById("student-list").innerHTML = output;
}
</script>
<!-- Button to trigger printing of JSON array -->
<button onclick="printStudents()">Print Students</button>
<!-- Div to display the JSON array -->
<div id="student-list"></div>
<!-- Footer for navigation -->
<footer>
<p><a href="page2.html">Go to Page 2</a></p>
</footer>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Read Data from JSON File</title>
</head>
<body>
<h1>Read Data from JSON File</h1>
<!-- Script to read data from JSON file and display it on the webpage -->
<script>
// Function to read data from JSON file and display it
function loadData() {
// Fetch JSON file
fetch('data.json')
.then(response => response.json())
.then(data => {
// Display data on the webpage
document.getElementById("data-container").innerHTML = "<pre>" + JSON.stringify(data, null, 2) + "</pre>";
})
.catch(error => console.error('Error fetching data:', error));
}
</script>
<!-- Button to trigger loading of data -->
<button onclick="loadData()">Load Data</button>
<!-- Container to display data from JSON file -->
<div id="data-container"></div>
<!-- Footer for navigation -->
<footer>
<p><a href="page1.html">Back to Page 1</a></p>
<p><a href="page3.html">Go to Page 3</a></p>
</footer>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Messages Formatting Using JSON</title>
</head>
<body>
<h1>Messages Formatting Using JSON</h1>
<!-- Script to demonstrate message formatting using JSON -->
<script>
var messages = {
"welcome": {
"text": "Welcome to our website!",
"color": "blue"
},
"error": {
"text": "An error occurred. Please try again later.",
"color": "red"
},
"success": {
"text": "Operation successful!",
"color": "green"
}
};
// Function to display formatted messages
function displayMessage(type) {
var message = messages[type];
var output = "<p style='color: " + message.color + "'>" + message.text + "</p>";
document.getElementById("message-container").innerHTML = output;
}
</script>
<!-- Buttons to trigger different types of messages -->
<button onclick="displayMessage('welcome')">Show Welcome Message</button>
<button onclick="displayMessage('error')">Show Error Message</button>
<button onclick="displayMessage('success')">Show Success Message</button>
<!-- Container to display messages -->
<div id="message-container"></div>
<!-- Footer for navigation -->
<footer>
<p><a href="page2.html">Back to Page 2</a></p>
</footer>
</body>
</html>