A Guide To Mastering html5 css3 and Javascript
A Guide To Mastering html5 css3 and Javascript
and JavaScript
WEB EXPERIENCE USING CUTTING-EDGE TOOLS
ZIGGY RAFIQ
All rights reserved. No part of this publication may be reproduced, distributed or transmitted in
any form or by any means, including photocopying, recording, or other electronic or mechanical
methods, without the prior written permission of the publisher, except in the case of brief
quotations embodied in critical reviews and certain other noncommercial uses permitted by
copyright law. Although the author/co-author and publisher have made every effort to ensure
that the information in this book was correct at press time, the author/co-author and publisher do
not assume and hereby disclaim any liability to any party for any loss, damage, or disruption
caused by errors or omissions, whether such errors or omissions result from negligence,
accident, or any other cause. The resources in this book are provided for informational purposes
only and should not be used to replace the specialized training and professional judgment of a
health care or mental health care professional. Neither the author/co-author nor the publisher
can be held responsible for the use of the information provided within this book. Please always
consult a trained professional before making any decision regarding the treatment of yourself or
others.
https://www.c-harpcorner.com/ebooks/ 2
Background and Expertise
Over the course of his 19 years of experience, Ziggy Rafiq has demonstrated exceptional skills
in System Architecture. With over 19 years of experience, he is a highly accomplished Full-
Stack Designer and Developer. In 2004, he was appointed Technical Lead Developer,
highlighting his leadership and expertise.
Several prestigious awards have recognized Ziggy Rafiq's exceptional talents. After he
developed an impenetrable login system in 2002, he received the Shell Award for his
groundbreaking work. In 2008, he was honored as one of Microsoft's Top 10 Developers in the
West Midlands at the Microsoft Hero Event.
Ziggy Rafiq has been recognized by C# Corner as a MVP, VIP, and Member of the Month (July),
as well as an active speaker and Chapter Lead at the UK Developer Community.
Educational background
As a student at college, Ziggy Rafiq earned an American Associate Degree in Interactive
Multimedia Communication. Continuing his education at the University of Wolverhampton from
1999 to 2003, he earned a BA Hons degree in Interactive Multimedia Communication 2:1. He
gained a comprehensive understanding of Design, Development, Testing, Deployment, and
Project Management along the way, making him an effective professional.
https://www.c-harpcorner.com/ebooks/ 3
Acknowledgement
Dedicated to author Ziggy Rafiq's late mother, Mrs. Zubeda Begum, whose unwavering love,
support, and encouragement have been a constant source of inspiration. From January 1st,
1950, to December 1st, 2022, her presence in Ziggy Rafiq's life shaped Ziggy Rafiq's journey,
and this book is a tribute to her memory.
Special Thanks
Ziggy Rafiq extends his heartfelt gratitude to the following individuals and communities who
have supported Ziggy Rafiq throughout the journey of creating this book.
— Ziggy Rafiq
https://www.c-harpcorner.com/ebooks/ 4
Table of Contents:
An Overview of HTML5 ................................................................................................................. 6
HTML5 Document Structure .........................................................................................................10
HTML5 Elements .........................................................................................................................14
HTML5 Graphics and Animation ...................................................................................................18
HTML5 APIs ................................................................................................................................22
HTML5 Multimedia ......................................................................................................................26
HTML5 Forms and Validation........................................................................................................30
HTML5 Accessibility .....................................................................................................................34
CSS3 and Styling ..........................................................................................................................37
HTML5 and JavaScript ..................................................................................................................41
Building Modern Web Application ................................................................................................45
Best Practices and Optimization ...................................................................................................50
Future Trends in HTML5 ...............................................................................................................54
HTML5 Reference Guide ..............................................................................................................58
https://www.c-harpcorner.com/ebooks/ 5
1
An Overview of HTML5
Overview
https://www.c-harpcorner.com/ebooks/ 6
What exactly is HTML5?
HTML5, also known as Hypertext Markup Language 5, is the most up-to-date and sophisticated
version of the HTML standard. It acts as the foundational technology utilized to structure and
display content on the Internet. In contrast to its predecessors, HTML5 is a major step forward,
offering a wide range of features and capabilities that empower web developers to create more
dynamic, interactive, and multimedia-rich websites and applications.
HTML5 is not an independent technology, but rather a combination of various web technologies,
such as HTML, CSS (Cascading Style Sheets), and JavaScript. It introduces a variety of fresh
elements, attributes, and APIs (Application Programming Interfaces) that enhance the process
of web development and provide improved support for contemporary web content and
functionality. Through HTML5, web developers are able to unleash their creative potential and
construct innovative online experiences that captivate and engage users.
Meaningful Elements
HTML5 incorporates fresh meaningful elements like <header>, <nav>, <section>, and <footer>
that provide a more organized and significant approach to defining the content and layout of web
pages. These elements enhance accessibility and search engine optimization.
https://www.c-harpcorner.com/ebooks/ 7
Canvas
The <canvas> element allows developers to create graphics, animations, and interactive
visualizations directly within the browser using JavaScript. It has unlocked new possibilities for
developing web-based games and multimedia applications.
Local Storage
HTML5 introduces the local Storage and session Storage APIs, enabling web applications to
store data locally on a user's device. This feature is invaluable for creating web apps that can
function offline and for improving performance.
Location Services
HTML5 provides a Geolocation API that allows web applications to access a user's location.
This feature is frequently utilized in mapping and location-based services.
Web Workers
Web Workers are a mechanism for executing scripts in the background, separate from the
primary thread of the web page. They enable multi-threading in web applications, enhancing
performance and responsiveness.
Adaptive Design
HTML5 promotes the use of responsive web design techniques, facilitating the creation of
websites that adapt to various screen sizes and devices, such as smartphones and tablets.
Enhanced Forms
HTML5 introduces new input types (e.g., <input type="email">, <input type="date">) and
attributes (e.g., required, placeholder) that improve the usability and validation of web forms.
Inclusive Accessibility
HTML5 strongly emphasizes accessibility, offering features like ARIA (Accessible Rich Internet
Applications) attributes and improved support for assistive technologies. This ensures that web
content is inclusive and usable by everyone.
WebSocket’s
HTML5 supports WebSocket’s, enabling real-time, bidirectional communication between the
browser and server. This is essential for developing interactive web applications like chat
applications and online gaming.
HTML5 represents a significant advancement in web technology, providing a strong foundation
for building modern, feature-rich web applications and websites. In the subsequent sections of
https://www.c-harpcorner.com/ebooks/ 8
this book, we will explore the various aspects of HTML5 in detail, including its elements,
attributes, and APIs, and demonstrate how to harness its capabilities to create engaging web
experiences.
https://www.c-harpcorner.com/ebooks/ 9
2
HTML5 Document Structure
Overview
https://www.c-harpcorner.com/ebooks/ 10
HTML Document Structure
A document written in HTML (Hypertext Markup Language) has a well-defined structure that is
outlined by several components. To be able to create a well-organized and semantically
meaningful web page, it is crucial that we understand the structure of an HTML5 document. Our
goal in this chapter is to provide code examples that illustrate each element's usage in an
HTML5 document and explain the key components.
<!DOCTYPE html>
The purpose of this declaration is to inform a web browser that the document adheres to the
HTML5 specification and to help ensure that the browser parses the content correctly and that
the appropriate parsing rules are applied.
<!DOCTYPE html>
<html>
<head>
<title>Example of HTML5 Document</title>
</head>
<body>
<!-- Content goes here -->
</body>
</html>
<meta>
<meta> elements are used for specifying character encoding as well as other information related
to a document.
https://www.c-harpcorner.com/ebooks/ 11
<title>
<title>A title element is used to set the title of a web page (displayed in the browser's title bar or
tab) that appears on the page.
<link>
<link> A link element refers to an external stylesheet (CSS) that is referenced with the link>
element.
<script>
elements for including JavaScript files.
Metadata elements for search engine optimization (SEO) and social media sharing (e.g., Open
Graph tags).
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Example of HTML5 Page</title>
<link rel="stylesheet" href="styles.css">
<script src="script.js"></script>
</head>
<body>
<!-- Content goes here -->
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Example of HTML5 Page</title>
</head>
<body>
<header>
<h1>Welcome to Ziggy Rafiq Website</h1>
</header>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
https://www.c-harpcorner.com/ebooks/ 12
</nav>
<main>
<section>
<h2>About Us</h2>
<p>We are a creative and innovative team...</p>
</section>
<section>
<h2>Contact Us</h2>
<p>Feel free to reach out to us...</p>
</section>
</main>
<footer>
© 2023 Ziggy Rafiq Website
</footer>
</body>
</html>
A well-structured and semantically meaningful web page relies on understanding the structure of
an HTML5 document. We will explore HTML5's features and elements in the following chapters,
including creating interactive forms, multimedia content, and responsive layouts.
https://www.c-harpcorner.com/ebooks/ 13
3
HTML5 Elements
Overview
https://www.c-harpcorner.com/ebooks/ 14
Among the many features and enhancements brought by HTML5, the fifth major version of the
Hypertext Markup Language, were several new features and enhancements. Three major
categories of HTML5 elements are covered in this chapter: Semantic Elements, Multimedia
Elements, and Form Elements and Improvements. To illustrate their use, we'll provide practical
code examples for each category.
Semantic Elements
The semantic elements introduced by HTML5 provide a clearer and more meaningful structure
for web documents. These elements enhance the accessibility and SEO-friendliness of web
pages by describing the content's purpose.
https://www.c-harpcorner.com/ebooks/ 15
Section (<section>) Element
The element defines a standalone section of content within a document. It usually is used to
group related content together, providing a clear structure for the page.
<section>
<h2>About Us</h2>
<p>We are a company dedicated to...</p>
</section>
Multimedia Elements
The HTML5 standard introduced several multimedia elements that allow us to embed audio,
video, and graphics directly into our website, reducing the need for third-party plugins.
https://www.c-harpcorner.com/ebooks/ 16
Canvas (<canvas>) Element
This element is used for drawing graphics, animations, and interactive content directly within our
web page using JavaScript.
<canvas id="exampleCanvas" width="400" height="200"></canvas>
<script>
var canvas = document.getElementById('exampleCanvas');
var context = canvas.getContext('2d');
// Use JavaScript to draw on the canvas
</script>
Placeholder Text
Placeholder attributes make it clear to users what information is expected from form fields by
providing hints or example texts.
<input type="text" placeholder="Enter your email">
Web development has been revolutionized by HTML5's semantic, multimedia, and form
elements, which provide greater clarity, interactivity, and accessibility. With these elements and
improvements, we can create more user-friendly, SEO-friendly, and visually engaging web
pages. The next chapter will explore CSS3, which adds styling and animations to web content in
addition to HTML5.
https://www.c-harpcorner.com/ebooks/ 17
4
HTML5 Graphics and
Animation
Overview
https://www.c-harpcorner.com/ebooks/ 18
HTML5 has brought forth a variety of potent tools and methods for crafting visually captivating
and interactive web content in this section. In this section, we will delve into the realm of HTML5
graphics and animation. We will discuss Scalable Vector Graphics (SVG), the <canvas>
element, and CSS animation and transitions.
You can generate shapes, text, gradients, and more using SVG. It can be directly embedded in
your HTML or referenced externally.
Interactive SVG
By utilizing JavaScript, you can make SVG graphics interactive, responding to user interactions
such as hovers and clicks.
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" fill="blue" id="myCircle" />
</svg>
<script>
var circle = document.getElementById('myCircle');
circle.addEventListener('click', function() {
circle.setAttribute('fill', 'green');
});
</script>
https://www.c-harpcorner.com/ebooks/ 19
var context = canvas.getContext('2d');
context.fillStyle = 'blue';
context.fillRect(10, 10, 100, 50);
</script>
The canvas graphics are drawn programmatically using JavaScript, which provides you with
meticulous control over every pixel.
Canvas Animation
To create seamless animations, you can redraw the canvas at regular intervals. Here's a basic
animation example:
<canvas id="myCanvas" width="200" height="100"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var x = 10;
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = 'blue';
context.fillRect(x, 10, 100, 50);
x += 2;
requestAnimationFrame(draw);
}
draw();
</script>
CSS Transitions
With CSS transitions, you can smoothly alter the properties of an element over time. Here's an
example that transitions the background color of a button when the user hovers over it.
.button {
background-color: blue;
transition: background-color 0.3s ease;
}
.button:hover {
background-color: red;
}
https://www.c-harpcorner.com/ebooks/ 20
CSS Keyframe Animations
With CSS animations, you can fabricate more intricate animations by specifying keyframes and
animation properties. Here's an example of a rotating animation.
@keyframes rotate {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.rotate {
animation: rotate 2s linear infinite;
}
CSS animations and transitions elevate the user's experience by incorporating smooth and
visually appealing effects.
Here, we have delved into the extensive graphics and animation options available in HTML5.
You can employ Scalable Vector Graphics (SVG) for generating vector graphics, canvas
elements for bitmap graphics, CSS for transitions and animations, and a wide array of tools with
HTML5 to generate your web content. Our subsequent section will concentrate on responsive
web design, ensuring that your web pages can gracefully adapt to diverse screen sizes.
https://www.c-harpcorner.com/ebooks/ 21
5
HTML5 APIs
Overview
Explore the exciting world of HTML5 APIs in this chapter, where you'll
discover powerful tools that enhance your web creations. From
handling multimedia with ease to crafting interactive experiences,
HTML5 APIs empower your web pages with dynamic features. Learn
to integrate these tools seamlessly into your projects, bringing your
websites to life with the latest web technologies.
https://www.c-harpcorner.com/ebooks/ 22
The HTML5 APIs (Application Programming Interfaces) allow web developers to enhance the
functionality and interactivity of web applications in this section. We will provide comprehensive
explanations and practical code illustrations for four crucial HTML5 APIs: Geolocation, Web
Storage, Drag and drop, and Web Workers.
Geolocation API
To create applications that are aware of the user's location, developers are provided with
latitude and longitude coordinates through the Geolocation API. Here is how to utilize the API.
https://www.c-harpcorner.com/ebooks/ 23
Storing Data in localStorage
// Storing data
localStorage.setItem("username", "john_doe");
// Retrieving data
var username = localStorage.getItem("username");
console.log("Username: " + username);
// Removing data
localStorage.removeItem("username");
// Retrieving data
var sessionID = sessionStorage.getItem("sessionID");
console.log("Session ID: " + sessionID);
// Removing data
sessionStorage.removeItem("sessionID");
HTML Structure
<div id="drag-source" draggable="true">
Drag this element
</div>
<div id="drop-target">
Drop here
</div>
dragSource.addEventListener("dragstart", function(event) {
event.dataTransfer.setData("text/plain", "Dragged Data");
});
dropTarget.addEventListener("dragover", function(event) {
https://www.c-harpcorner.com/ebooks/ 24
event.preventDefault();
});
dropTarget.addEventListener("drop", function(event) {
event.preventDefault();
var data = event.dataTransfer.getData("text/plain");
dropTarget.innerHTML = "Dropped: " + data;
});
Web Workers
The use of Web Workers in web applications allows time-consuming tasks to be executed in the
background without blocking the main UI thread, ensuring that the webpage remains
responsive.
worker.onmessage = function(event) {
console.log("Worker says: " + event.data);
};
As a result of these HTML5 APIs, developers can create location-aware applications, store data
locally, implement drag-and-drop interfaces, and manage background tasks efficiently. Web
applications can offer a more engaging and responsive user experience by utilizing these APIs.
In the following chapter, we will examine JavaScript frameworks and libraries for client-side
development, which simplify web development tasks and simplify the creation of dynamic web
applications.
https://www.c-harpcorner.com/ebooks/ 25
6
HTML5 Multimedia
Overview
https://www.c-harpcorner.com/ebooks/ 26
It has become essential to integrate multimedia content seamlessly into web pages. HTML5
introduced powerful features and APIs for seamlessly integrating multimedia content. We will
explore three main aspects of HTML5 multimedia in this section: Embedding sound and video,
Media APIs, and Adaptive images.
• Sound elements can be played, paused, and volume controlled using the controls
attribute.
• Multiple <source> elements are utilized to provide different formats for wider browser
compatibility.
Media APIs
With HTML5, developers can create customized media players and add programmatic control
using JavaScript APIs.
https://www.c-harpcorner.com/ebooks/ 27
Controlling Playback
var audioElement = document.querySelector("audio");
var videoElement = document.querySelector("video");
// Play
audioElement.play();
videoElement.play();
// Pause
audioElement.pause();
videoElement.pause();
Media Events
audioElement.addEventListener("play", function() {
console.log("Audio playback started");
});
videoElement.addEventListener("ended", function() {
console.log("Video playback ended");
});
Media Metadata
audioElement.addEventListener("loadedmetadata", function() {
console.log("Audio duration: " + audioElement.duration + "
seconds");
});
videoElement.addEventListener("loadedmetadata", function() {
console.log("Video duration: " + videoElement.duration + "
seconds");
});
Adaptive Images
The srcset and sizes attributes of HTML5 handle adaptive images in a manner that ensures a
consistent user experience regardless of screen size or resolution.
https://www.c-harpcorner.com/ebooks/ 28
Multiple image sources along with their respective widths are listed in the srcset attribute.
The displayed width of the image is determined based on viewport conditions by the sizes
attribute.
Browsers can select the most appropriate image source based on the device and screen size of
the user.
The web has been revolutionized by the multimedia capabilities and APIs of HTML5, allowing us
to embed and engage with audio, video, and visuals in new and exciting ways. Whether you're
building a personalized media player or optimizing images for various devices, HTML5 provides
the essential resources for an immersive and captivating multimedia encounter. In the upcoming
section, we will explore advanced subjects in web development, such as server-side scripting,
databases, and web security, in order to develop powerful and secure web applications.
https://www.c-harpcorner.com/ebooks/ 29
7
HTML5 Forms and
Validation
Overview
https://www.c-harpcorner.com/ebooks/ 30
There have been several enhancements to HTML5 that make it easier to create user-friendly
and interactive web forms. This chapter will cover three of the key aspects of HTML5 forms and
validation: New input types, form validation, and custom form controls.
Form Validation
Using HTML5's built-in form validation, you can reduce the need for custom JavaScript
validation. Attributes include required, min, max, pattern, and more.
Required Field
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
https://www.c-harpcorner.com/ebooks/ 31
Pattern Matching (Regular Expression)
<label for="zipcode">Zip Code:</label>
<input type="text" id="zipcode" name="zipcode" pattern="[0-9]{5}">
Custom Checkbox
<label for="custom-checkbox">Custom Checkbox:</label>
<input type="checkbox" id="custom-checkbox" class="custom-checkbox">
.custom-checkbox {
appearance: none; /* Remove default styles */
-webkit-appearance: none; /* For older versions of Safari */
width: 20px;
height: 20px;
background-color: #ccc;
border: 2px solid #666;
border-radius: 4px;
}
.custom-checkbox:checked {
background-color: #007bff;
border-color: #007bff;
}
https://www.c-harpcorner.com/ebooks/ 32
Custom Radio Buttons
<label>Gender:</label>
<input type="radio" id="male" name="gender" class="custom-radio">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" class="custom-radio">
<label for="female">Female</label>
.custom-radio {
appearance: none; /* Remove default styles */
-webkit-appearance: none; /* For older versions of Safari */
width: 20px;
height: 20px;
background-color: #ccc;
border: 2px solid #666;
border-radius: 50%;
}
.custom-radio:checked {
background-color: #007bff;
border-color: #007bff;
}
With HTML5, you can create user-friendly and interactive web forms, with a variety of input
types, validation options, and the flexibility to create custom control sets. With HTML5, your web
applications can collect and analyze data more effectively. We will discuss responsive design,
client-side scripting, and server-side security in the next chapter.
https://www.c-harpcorner.com/ebooks/ 33
8
HTML5 Accessibility
Overview
https://www.c-harpcorner.com/ebooks/ 34
People with disabilities can use web content because of accessibility, which is a crucial aspect
of web development. In addition to semantic markup, ARIA roles and attributes, and accessibility
testing, HTML5 provides a number of features and best practices for improving accessibility.
Links (<a>)
Make sure link text is descriptive and informative. Avoid using "click here" or non-informative link
text.
<a href="/about">About Us</a>
https://www.c-harpcorner.com/ebooks/ 35
ARIA Roles
ARIA roles specify the type of element and its purpose. For instance, role="button" indicates a
button element.
<button role="button" onclick="doSomething()">Click Me</button>
ARIA Attributes
ARIA attributes provide additional information about an element's state and properties. For
example, you can use aria-label to provide a label when the visible label is not sufficient.
<input type="text" aria-label="Search">
Browser DevTools
There are built-in accessibility inspection tools in most modern browsers that allow you to
examine the accessibility tree, view ARIA attributes, and identify problems.
Online Validators
There are several online tools and validators that can automatically check your web pages for
accessibility problems, including the WAVE Web Accessibility Evaluation Tool and the axe
DevTools.
Manual Testing
Using assistive technologies such as screen readers, you can test your web content manually
for accessibility issues.
<!-- Test your web page with a screen reader -->
<div aria-live="polite">
This is an accessible live region.
</div>
Automated Testing
Using tools like Pa11y or axe-core you can automate accessibility testing to catch issues early in
the development process.
# Command-line accessibility testing with Pa11y
pa11y https://example.com
Your web development process can be inclusive and accessible to users of all abilities by
incorporating semantic HTML5 elements, ARIA roles, and attributes, and thorough accessibility
testing. We will explore advanced web development concepts in the next chapter, including web
performance optimization, responsive design, and cross-browser compatibility.
https://www.c-harpcorner.com/ebooks/ 36
9
CSS3 and Styling
Overview
https://www.c-harpcorner.com/ebooks/ 37
With CSS3, the latest version of Cascading Style Sheets, web styling and layout were
revolutionized. The following key topics will be discussed in this chapter: CSS3 features and
enhancements, Flexbox, Grid layouts, and media queries for responsive design.
Transitions (transition)
By using transitions, you can add smooth animations to your elements when their state
changes.
/* Transition for a button */
button {
transition: background-color 0.3s ease;
}
button:hover {
background-color: #007bff;
}
https://www.c-harpcorner.com/ebooks/ 38
Flexbox
Flexbox simplifies alignment and distribution of elements in one-dimensional layouts. It is ideal
for arranging elements in rows and columns.
/* Flex container */
.container {
display: flex;
justify-content: space-between; /* Space items evenly */
align-items: center; /* Center items vertically */
}
/* Flex items */
.item {
flex: 1; /* Equal width for all items */
}
Grid Layout
Layouts with grids are great for two-dimensional layouts. They allow you to insert rows and
columns into the grid.
/* Grid container */
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr; /* Three equal columns */
grid-gap: 20px; /* Gap between grid items */
}
/* Grid items */
.item {
grid-column: span 2; /* Span two columns */
}
Responsive Navigation
https://www.c-harpcorner.com/ebooks/ 39
As a result of media queries, responsive navigation menus can be created that adapt to the
screen size of any device.
/* Hide the navigation menu on small screens */
@media (max-width: 768px) {
.nav-menu {
display: none;
}
}
You can create modern, responsive, and visually appealing web designs that adapt to a wide
range of devices and screen sizes by utilizing CSS3 features like Flexbox, Grid layout, and
media queries. These tools empower web developers to craft user-friendly and flexible layouts
that enhance the user experience with the use of these tools. To build robust and secure web
applications, we will explore advanced web development topics in the next chapter, including
client-side scripting, server-side scripting, and web security.
https://www.c-harpcorner.com/ebooks/ 40
10
HTML5 and JavaScript
Overview
https://www.c-harpcorner.com/ebooks/ 41
It has been proven that HTML5 and JavaScript are dynamic tools that enable web developers to
create interactive web applications that are responsive and interactive. In this chapter, we will
delve into three fundamental topics: using JavaScript with HTML5, manipulating the DOM
(Document Object Model) and asynchronous programming with Promises.
Inline JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Using JavaScript</title>
</head>
<body>
<h1>Hello, World!</h1>
<script>
// Inline JavaScript
alert("Welcome to JavaScript!");
</script>
</body>
</html>
External JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Using External JavaScript</title>
<script src="script.js"></script>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
DOM Manipulation
An HTML document's structure is represented by the DOM as a tree-like structure, and
JavaScript allows you to manipulate this structure dynamically. JavaScript allows you to access,
modify, or create HTML elements and their attributes.
https://www.c-harpcorner.com/ebooks/ 42
Accessing Elements
// Access an element by its ID
var element = document.getElementById("myElement");
// Access elements by class name
var elements = document.getElementsByClassName("myClass");
// Access elements by tag name
var elements = document.getElementsByTagName("div");
Modifying Elements
// Change the text content of an element
element.textContent = "New Text";
// Change the attribute of an element
element.setAttribute("src", "new-image.jpg");
// Create a new element and append it to the DOM
var newElement = document.createElement("p");
newElement.textContent = "This is a new paragraph.";
document.body.appendChild(newElement);
Event Handling
// Add an event listener to an element
element.addEventListener("click", function() {
alert("Element clicked!");
});
Creating a Promise
function fetchData() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
// Simulate fetching data
var data = { name: "John" };
resolve(data); // Resolve the promise with the data
}, 2000);
});
}
https://www.c-harpcorner.com/ebooks/ 43
Consuming a Promise
fetchData()
.then(function(data) {
console.log("Data received:", data);
})
.catch(function(error) {
console.error("Error:", error);
});
As well as HTML5, JavaScript can be used to develop dynamic and interactive web applications
as well. By learning how to integrate JavaScript with HTML5, manipulate the DOM, and work
with Promises for asynchronous programming, you will be prepared to create modern web
experiences. In the next chapter, we will discuss advanced web development topics, such as
server-side scripting, databases, and web security, in order to build robust and secure web
applications.
https://www.c-harpcorner.com/ebooks/ 44
11
Building Modern Web
Application
Overview
https://www.c-harpcorner.com/ebooks/ 45
A key aspect of this chapter is to look at the latest trends and technologies that are being used
in the development of modern web applications, such as Single Page Apps (SPAs), Progressive
Web Apps (PWAs), and popular frameworks and libraries for HTML5.
Dynamic Loading
A SPA loads data from the server only when necessary, reducing the initial loading time of a
page.
Client-Side Routing
To navigate between views without having to refresh the entire page, SPAs use client-side
routing.
State Management
State management libraries such as Redux or Mobx are often used by SPAs.
React
The React library was developed by Facebook to build user interfaces for SPAs.
Angular
A comprehensive framework for creating SPAs, Angular is developed by Google.
Vue.js
The simplicity and flexibility of Vue.js make it another popular choice for SPAs.
https://www.c-harpcorner.com/ebooks/ 46
Progressive Web Apps (PWA)
A Progressive Web App (PWA) provides users with a native app-like experience while providing
access to a native application via the web browser. PWAs include offline accessibility, push
notifications, and fast loading, making them a compelling choice for web development in the
modern age.
Manifest Files
Manifest files contain metadata about apps, including icons and splash screens.
Responsive Design
A PWA will work seamlessly across a wide range of devices and screens.
App-Like Experience
Animations and navigation are smooth in PWAs, just like in native apps.
https://www.c-harpcorner.com/ebooks/ 47
</script>
</body>
</html>
// manifest.json
{
"name": "My PWA",
"short_name": "PWA",
"description": "A Progressive Web App",
"start_url": "/",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#007bff",
"icons": [
{
"src": "/icon.png",
"sizes": "192x192",
"type": "image/png"
}
]
}
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
});
https://www.c-harpcorner.com/ebooks/ 48
React
This is due to the fact that React is well known for the efficiency with which it updates user
interfaces because of its component-based architecture and virtual DOM.
// Example React Component
import React from 'react';
Angular
JavaScript framework for building SPAs that provides tools for routing, state management, and
dependency injection.
// Example Angular Component
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: '<div>Hello, Angular!</div>'
})
export class AppComponent { }
Vue.js
A progressive framework for building user interfaces, Vue.js is known for its simplicity and
flexibility, making it easy to use as the code example below show us.
// Example Vue.js Component
<template>
<div>Hello, Vue.js!</div>
</template>
<script>
export default {
name: 'MyComponent'
}
</script>
In order to build a modern web application, you must choose the right architectural approach
(SPA or PWA) and select the right framework and library. Staying current with the latest trends
and tools is essential to delivering high-quality, responsive, and engaging web applications,
whether you use SPAs, PWAs, React, Angular, Vue.js, or another technology. To build robust
and secure web applications, we will explore server-side scripting, databases, and web security
in the next chapter.
https://www.c-harpcorner.com/ebooks/ 49
12
Best Practices and
Optimization
Overview
https://www.c-harpcorner.com/ebooks/ 50
This chapter explores the best practices and optimization techniques for HTML5 development,
including HTML5 performance tips, making HTML5 content SEO-friendly, and ensuring cross-
browser compatibility.
Optimize Images
Use responsive images with the srcset attribute to serve different image sizes depending on the
user's device. Compress and optimize images to reduce file sizes without compromising quality.
<img src="image.jpg" srcset="image-small.jpg 320w, image-medium.jpg
768w, image-large.jpg 1024w" alt="Responsive Image">
container.appendChild(fragment);
SEO-Friendly HTML5
https://www.c-harpcorner.com/ebooks/ 51
SEO (Search Engine Optimization) is crucial to making your HTML5 content search engine-
friendly. Follow these steps to make HTML5 content SEO-friendly:
Cross-Browser Compatibility
You should ensure your HTML5 content is cross-browser compatible for a wide audience. Here
are some cross-browser compatibility tips:
https://www.c-harpcorner.com/ebooks/ 52
} else {
// Fallback for older browsers
}
/* Vendor-prefixed property */
div {
-webkit-transition: -webkit-transform 0.3s;
transition: transform 0.3s;
}
To optimise your web content for performance, improve search engine visibility, and make sure
that it is compatible with as many browsers as possible, you should follow these HTML5
development best practices. The use of these practices will make it easier to deliver a seamless
and accessible web experience to a wide range of people.
https://www.c-harpcorner.com/ebooks/ 53
13
Future Trends in HTML5
Overview
https://www.c-harpcorner.com/ebooks/ 54
This chapter examines the future trends and advancements in HTML5 development, including
the adoption of web components, the rise of WebAssembly, and the ongoing evolution of
HTML5.
Web Components
A web component is a reusable and encapsulated custom HTML element. It allows you to build
complex web applications with modular and maintainable code. It consists of four main
technologies.
Custom Elements
A web component is a reusable and encapsulated custom HTML element. It allows you to build
complex web applications with modular and maintainable code. It consists of four main
technologies:
<!-- Define a custom element -->
<my-button></my-button>
customElements.define('my-button', MyButton);
Shadow DOM
The Shadow DOM allows web components to have their own isolated DOM tree and styles,
which prevents CSS and JavaScript conflicts between components and the rest of the page.
// Create a shadow DOM for a custom element
const shadow = this.attachShadow({ mode: 'open' });
HTML Templates
This is particularly useful for web components to define their structure through HTML templates,
which can be cloned and inserted into the DOM as needed.
<template id="my-template">
<style>
/* Styles specific to the template */
</style>
<div>
<!-- Content for the template -->
</div>
</template>
https://www.c-harpcorner.com/ebooks/ 55
HTML Imports (Deprecated)
Web components used to be able to include external HTML files as dependencies, but that
feature has been deprecated in favour of ES modules.
Developers are increasingly creating custom elements with encapsulated functionality, so
complex applications can be managed more easily. Web components enable developers to
create modular, maintainable, and shareable web applications.
WebAssembly
With WebAssembly (Wasm), code can be executed in a web browser with high performance. By
enabling complex computations, gaming, and more, WebAssembly will make it possible to
compile languages other than JavaScript for near-native performance in the browser. By
enabling complex computations, gaming, and more, WebAssembly will have a significant impact
on web development.
WebAssembly Benefits
The following examples demonstrate performance, cross-platform, and the use of WebAssembly
in a simple way.
Performance
Code is executed at near-native speed using WebAssembly, making web applications more
responsive and faster.
Cross-Platform
There are a number of major browsers that support WebAssembly, making it a cross-platform
solution.
This platform is language agnostic, meaning developers can use any programming language
they choose.
Using WebAssembly
You load WebAssembly binary format (.wasm) into your JavaScript code in order to use
WebAssembly in your web application.
In addition to high-performance gaming, scientific simulations, and running legacy code in the
browser, WebAssembly opens up a world of possibilities for web applications.
https://www.c-harpcorner.com/ebooks/ 56
HTML Modules
In web applications, HTML modules provide a modular and efficient way to load and manage
scripts. This feature is still in the proposal stage, but promise to simplify script management.
Accessibility Improvements
Web accessibility is a growing focus in web development. HTML5 will introduce more
accessibility features and improvements so that everyone can use web content.
https://www.c-harpcorner.com/ebooks/ 57
Appendix
HTML5 Reference Guide
https://www.c-harpcorner.com/ebooks/ 58
This appendix acts as an extensive guidebook for HTML5, encompassing tags and attributes,
CSS3 properties, and JavaScript API mentions. Regardless of whether you are a novice in need
of a quick reference or an experienced developer in search of a refresher, this guide will prove
to be a valuable resource.
<header>
Serves as a container for introductory content or a set of navigation links.
<nav>
Defines a section with navigation links.
<section>
Represents an independent section of content within a document.
<article>
Defines a self-contained composition within a document.
<aside>
Represents content that tangentially relates to the surrounding content.
<footer>
Defines a footer for a section or a page.
<figure>
Represents any content that is referenced from the main content.
<figcaption>
Supplies a caption or legend for a <figure> element.
<main>
Specifies the primary content of a document.
https://www.c-harpcorner.com/ebooks/ 59
Frequent HTML5 Attributes
data-*
Custom data attributes that can store additional information.
aria-*
ARIA attributes for enhancing accessibility.
role
Defines the purpose of an element in an ARIA accessibility context.
contenteditable
Allows the user to edit an element.
autocomplete
Specifies whether the browser should automatically complete input values.
required
Indicates that an input field must be completed before submitting a form.
For a complete compilation of HTML5 tags and attributes, refer to the official W3C HTML Living
Standard documentation.
CSS3 Properties
CSS3 brought forth a plethora of novel properties and features for styling web content. Here are
some commonly employed CSS3 properties.
border-radius
Defines rounded corners for elements.
box-shadow
Adds shadows to elements.
transition
Specifies the transition effects for changes in element properties.
https://www.c-harpcorner.com/ebooks/ 60
transform
Applies 2D or 3D transformations to elements.
@media
Defines media queries for responsive design.
flexbox
A flexible layout model for arranging elements within a container.
:hover
Applies styles when the mouse hovers over an element.
:nth-child()
Selects elements based on their position within a parent.
document.getElementById()
Retrieves an element based on its ID.
document.querySelector()
element.addEventListener()
Binds an event listener to an element.
https://www.c-harpcorner.com/ebooks/ 61
element.innerHTML
Obtains or modifies the HTML content of an element.
element.style
Accesses or changes the CSS styles of an element.
Fetch API
fetch()
Initiates server requests and returns Promises for handling responses.
localStorage
Stores data persistently in a web browser using key-value pairs.
sessionStorage
Stores data for the duration of a page session using key-value pairs.
Canvas API
<canvas>
An HTML5 element for rendering graphics and animations.
context.drawImage()
Draws an image, video, or canvas onto the canvas.
Geolocation API
navigator.geolocation.getCurrentPosition()
Retrieves the geographic position of the device.
Worker()
Creates a web worker to execute JavaScript code in the background.
https://www.c-harpcorner.com/ebooks/ 62
IndexedDB API
indexedDB
Provides a low-level API for storing structured data in browsers.
AudioContext()
Represents an audio-processing graph.
AudioBufferSourceNode
Represents an audio source that can be played.
AudioAnalyserNode
Analyses audio data, useful for creating visualisations.
Element.animate()
Creates and controls animations on elements.
Animation
Represents a single animation, which can be controlled and manipulated.
WebRTC API
RTCPeerConnection
Enables real-time communication, such as video and audio calls, directly in the browser.
Notifications API
Notification.requestPermission()
Requests permission to display browser notifications.
new Notification()
Creates and shows notifications to the user.
History API
https://www.c-harpcorner.com/ebooks/ 63
history.pushState()
Adds a state to the browser's history stack.
history.replaceState()
Replaces the current state in the history stack.
WebSockets API
WebSocket()
Creates a WebSocket object for real-time, bidirectional communication between client and
server.
Fullscreen API
Element.requestFullscreen()
Requests to display an element in fullscreen mode.
document.exitFullscreen()
Leaves fullscreen mode.
EventSource()
Establishes a connection for receiving server-sent events.
File API
File
Represents a file selected by the user.
FileReader
Reads the contents of a file asynchronously.
navigator.getVRDisplays()
Retrieves information about available VR displays.
https://www.c-harpcorner.com/ebooks/ 64
WebXR API
navigator.xr.requestSession()
Requests an XR (extended reality) session for VR or AR experiences.
These JavaScript APIs enable web developers to create a wide array of interactive and
immersive web experiences, ranging from audio and video processing to real-time
communication and virtual reality applications.
SpeechRecognition()
Initializes a speech recognition instance for converting spoken language into text.
SpeechSynthesisUtterance()
Represents a speech request for text-to-speech synthesis.
IntersectionObserver()
Monitors elements for changes in their intersection with an ancestor element or the viewport.
ResizeObserver()
Observes modifications to the size of an element's content or the dimensions of its container.
Clipboard API
Clipboard.writeText()
Writes text to the system clipboard.
Clipboard.readText()
Extracts text from the system clipboard.
Gamepad API
navigator.getGamepads()
Retrieves details about connected gamepads and their current state.
https://www.c-harpcorner.com/ebooks/ 65
Battery Status API (deprecated)
navigator.getBattery()
Fetches details about the device's battery status (deprecated in favor of the Battery Status Event
API).
navigator.getBattery()
Fetches details about the device's battery status using Promises and events.
Beacon API
navigator.sendBeacon()
Transmits data to a web server asynchronously with a promise that resolves when the data has
been successfully queued for transmission.
BroadcastChannel()
Facilitates communication between different browsing contexts (e.g., tabs or iframes) with the
same origin.
navigator.credentials.create()
Creates a new public key credential for user authentication.
navigator.credentials.get()
Retrieves a public key credential for user authentication.
PaymentRequest()
Enables websites to request payment information and securely process payments.
navigator.connection.effectiveType
https://www.c-harpcorner.com/ebooks/ 66
Provides information about the effective network connection type (e.g., "4g," "3g," "2g").
showOpenFilePicker()
Allows users to select files from their local file system.
showSaveFilePicker()
Allows users to store files in their local file system.
This HTML5 Reference Guide serves as an essential companion for web developers at all
levels. Offering immediate access to crucial HTML5 tags, attributes, CSS3 properties, and
JavaScript API references, it equips you with the knowledge required to navigate the HTML5
landscape effectively. Whether you're starting a new web project or maintaining an existing one,
this guide is your reliable companion.
These JavaScript APIs represent only a glimpse of the extensive toolkit available to web
developers. For a comprehensive understanding of JavaScript APIs and their capabilities, the
Mozilla Developer Network (MDN) JavaScript Reference is an invaluable resource.
It's important to note that official documentation and resources, such as those offered by the
Mozilla Developer Network (MDN) and other reputable sources, are invaluable references when
working with JavaScript APIs. Staying up to date with the latest API features and adhering to
best practices is crucial for success in the ever-evolving field of web development.
https://www.c-harpcorner.com/ebooks/ 67
OUR MISSION
Free Education is Our Basic Need! Our mission is to empower millions of developers worldwide by
providing the latest unbiased news, advice, and tools for learning, sharing, and career growth. We’re
passionate about nurturing the next young generation and help them not only to become great
programmers, but also exceptional human beings.
ABOUT US
CSharp Inc, headquartered in Philadelphia, PA, is an online global community of software
developers. C# Corner served 29.4 million visitors in year 2022. We publish the latest news and articles
on cutting-edge software development topics. Developers share their knowledge and connect via
content, forums, and chapters. Thousands of members benefit from our monthly events, webinars,
and conferences. All conferences are managed under Global Tech Conferences, a CSharp
Inc sister company. We also provide tools for career growth such as career advice, resume writing,
training, certifications, books and white-papers, and videos. We also connect developers with their poten-
tial employers via our Job board. Visit C# Corner
MORE BOOKS