0% found this document useful (0 votes)
2 views28 pages

Unit 3

HTML5 is the latest version of Hypertext Markup Language, enhancing web page design with new multimedia features, semantic elements, and APIs. It introduces web storage capabilities, allowing local data storage, and supports real-time communication through WebSockets and Server-Sent Events. CSS3, an advanced version of Cascading Style Sheets, offers improved styling options and modular standards for easier use and learning.

Uploaded by

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

Unit 3

HTML5 is the latest version of Hypertext Markup Language, enhancing web page design with new multimedia features, semantic elements, and APIs. It introduces web storage capabilities, allowing local data storage, and supports real-time communication through WebSockets and Server-Sent Events. CSS3, an advanced version of Cascading Style Sheets, offers improved styling options and modular standards for easier use and learning.

Uploaded by

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

HTML5

Introduction: HTML stands for Hyper Text Markup Language. It is used to design
web pages using a markup language. HTML is an abbreviation of Hypertext and
Markup language. Hypertext defines the link between the web pages. The
markup language is used to define the text document within the tag which
defines the structure of web pages. HTML 5 is the fifth and current version of
HTML. It has improved the markup available for documents and has introduced
application programming interfaces (API) and Document Object Model (DOM).
Features:
 It has introduced new multimedia features which supports both audio and
video controls by using <audio> and <video> tags.
 There are new graphics elements including vector graphics and tags.
 Enrich semantic content by including <header> <footer>, <article>,
<section> and <figure> are added.
 Drag and Drop- The user can grab an object and drag it further dropping it
to a new location.
 Geo-location services- It helps to locate the geographical location of a
client.
 Web storage facility which provides web application methods to store data
on the web browser.
 Uses SQL database to store data offline.
 Allows drawing various shapes like triangle, rectangle, circle, etc.
 Capable of handling incorrect syntax.
 Easy DOCTYPE declaration i.e., <!doctype html>
 Easy character encoding i.e., <meta charset=”UTF-8″>
Removed elements from HTML 5: There are many elements which are
depreciated from HTML 5 are listed below:

Removed Use Instead


Elements Elements

<acronym> <abbr>

<applet> <object>

<basefont> CSS

<big> CSS
Removed Use Instead
Elements Elements

<center> CSS

<dir> <ul>

<font> CSS

<frame>

<frameset>

<noframes>

<isindex>

<strike> CSS, <s> or <del>

<tt> CSS

New Added Elements in HTML 5:


 <article>: The <article> tag is used to represent an article. More
specifically, the content within the <article> tag is independent from the
other content of the site (even though it can be related).
 <aside>: The <aside> tag is used to describe the main object of the web
page in a shorter way like a highlighter. It basically identifies the content
that is related to the primary content of the web page but does not
constitute the main intent of the primary page. The <aside> tag contains
mainly author information, links, related content and so on.
 <figcaption>: The <figcaption> tag in HTML is used to set a caption to
the figure element in a document.
 <figure>: The <figure> tag in HTML is used to add self-contained content
like illustrations, diagrams, photos or codes listing in a document. It is
related to main flow, but it can be used in any position of a document and
the figure goes with the flow of the document and if it is removed it should
not affect the flow of the document.
 <header>: It contains the section heading as well as other content, such
as a navigation links, table of contents, etc.
 <footer>: The <footer> tag in HTML is used to define a footer of HTML
document. This section contains the footer information (author
information, copyright information, carriers etc.). The footer tag is used
within body tag. The <footer> tag is new in the HTML 5. The footer
elements require a start tag as well as an end tag.
 <main>: Delineates the main content of the body of a document or web
app.
 <mark>: The <mark> tag in HTML is used to define the marked text. It is
used to highlight the part of the text in the paragraph.
 <nav>: The <nav> tag is used to declaring the navigational section in
HTML documents. Websites typically have sections dedicated to
navigational links, which enables user to navigate the site. These links can
be placed inside a nav tag.
 <section>: It demarcates a thematic grouping of content.
 <details>: The <details> tag is used for the content/information which is
initially hidden but could be displayed if the user wishes to see it. This tag
is used to create interactive widget which user can open or close it. The
content of details tag is visible when open the set attributes.
 <summary>: The <summary> tag in HTML is used to define a summary
for the <details> element. The <summary> element is used along with
the <details> element and provides a summary visible to the user. When
the summary is clicked by the user, the content placed inside the
<details> element becomes visible which was previously hidden. The
<summary> tag was added in HTML 5. The <summary> tag requires both
starting and ending tag.
 <time>: The <time> tag is used to display the human-readable
data/time. It can also be used to encode dates and times in a machine-
readable form. The main advantage for users is that they can offer to add
birthday reminders or scheduled events in their calendars and search
engines can produce smarter search results.
 <wbr>: The <wbr> tag in HTML stands for word break opportunity and is
used to define the position within the text which is treated as a line break
by the browser. It is mostly used when the used word is too long and there
are chances that the browser may break lines at the wrong place for fitting
the text.
 <datalist>: The <datalist> tag is used to provide autocomplete feature
in the HTML files. It can be used with input tag, so that users can easily fill
the data in the forms using select the data.
 <keygen>: The <keygen> tag in HTML is used to specify a key-pair
generator field in a form. The purpose of <keygen> element is to provide
a secure way to authenticate users. When a form is submitted then two
keys are generated, private key and public key. The private key stored
locally, and the public key is sent to the server. The public key is used to
generate client certificate to authenticate user in future.
 <output>: The <output> tag in HTML is used to represent the result of a
calculation performed by the client-side script such as JavaScript.
 <progress>: It is used to represent the progress of a task. It also defines
how much work is done and how much is left to download a task. It is not
used to represent the disk space or relevant query.
 <svg>: It is the Scalable Vector Graphics.
 <canvas>: The <canvas> tag in HTML is used to draw graphics on web
page using JavaScript. It can be used to draw paths, boxes, texts, gradient
and adding images. By default, it does not contain border and text.
 <audio>: It defines the music or audio content.
 <embed>: Defines containers for external applications (usually a video
player).
 <source>: It defines the sources for <video> and <audio>.
 <track>: It defines the tracks for <video> and <audio>.
 <video>: It defines the video content.

CSS3:
CSS3 stands for Cascading Style Sheets Level 3. It is an advanced version of CSS,
used for structuring, styling, and formatting web pages. CSS3 introduces several
new features and is supported by all modern web browsers. One of the most
significant advancements in CSS3 is the splitting of CSS standards into separate
modules, making it simpler to learn and use.
New Features of CSS3
1. Combinator: CSS3 introduces a new general sibling combinator, which
matches sibling elements using the tilde (~) combinator.
2. CSS Selectors: CSS3 selectors are more advanced than the simple
selectors offered by CSS, providing a sequence of easy-to-use and simple
selectors.
3. Pseudo-elements: CSS3 adds many new pseudo-elements for easier and
more detailed styling. The new convention of double colons (::) is also
introduced.
4. Border Style: CSS3 includes new border styling features like border-
radius, border-image-slice, border-image-source, and values for “width
stretch”.
5. Background Style Properties: CSS3 introduces new background style
properties such as background-clip, background-size, background-style,
and background-origin.

HTML Web Storage


The Web Storage is one of the great features of HTML5. With the Web Storage
feature, web applications can locally store data within the browser on the client
side. It stores data in the form of key/value pair on the browser. Web Storage
sometimes also known as DOM storage.
Storing data with the help of web storage is similar to cookies, but it is better and
faster than cookies storage.

In HTML5 there are two types of web storage API.


 local Storage
 Session Storage
localStorage: It is used to store data on the client side. It has no expiration
time, so the data in the LocalStorage exists always till the user manually deletes
it.
Syntax:
 For storing data in web storage: The key and value both should be
string or number;
LocalStorage.setItem("key", "value");
 For getting data from web storage: We will pass the key and it will
return value.
LocalStorage.getItem("key");

Session Storage: It is used to store data on the client-side. Data in the


SessionStorage exist till the current tab is open, if we close the current tab then
our data will also erase automatically from the SessionStorage.
Syntax:
 For storing data in web storage:
SessionStorage.setItem("key", "value");
 For getting data from web storage:
SessionStorage.getItem("key");

WebSocket
WebSocket is bidirectional, a full-duplex protocol that is used in the same
scenario of client-server communication, unlike HTTP which starts
from ws:// or wss://. It is a stateful protocol, which means the connection
between client and server will stay alive until it gets terminated by either party
(client or server). After closing the connection by either of the client or server,
the connection is terminated from both ends.
Let’s take an example of client-server communication, there is the client which is
a web browser, and a server, whenever we initiate the connection between client
and server, the client-server makes the handshaking and decides to create a new
connection and this connection will keep alive until terminated by any of them.
When the connection is established and alive the communication takes place
using the same connection channel until it is terminated.
This is how after client-server handshaking, the client-server decides to keep a
new connection alive, this new connection will be known as WebSocket. Once the
communication link is established and the connections are opened, message
exchange will take place in bidirectional mode until the connection persists
between client-server. If anyone of them (client-server) dies or decide to close
the connection then it is closed by both the party. The way in which the socket
works is slightly different from how HTTP works, the status code 101 denotes the
switching protocol in WebSocket.

When can a web socket be used?


 Real-time web application
 Gaming application
 Chat application

What is Server-Sent Events in HTML5 ?


Server-Sent events (SSE) provide a seamless way to automatically update
web pages without requiring user interaction. These events allow servers to
push real-time data to clients over HTTP connections.
The updates for any website come via HTTP connections. This way of
communication of updating the webpage by a server to the client side is known
as one-way messaging or mono-directional. The Server-Sent Events are part of
web APIs.
HTML Canvas Tag
The HTML canvas element provides HTML a bitmapped surface to work with. It
is used to draw graphics on the web page.
The HTML 5 <canvas> tag is used to draw graphics using scripting language
like JavaScript.
The <canvas> element is only a container for graphics, you must need a
scripting language to draw the graphics. The <canvas> element allows for
dynamic and scriptable rendering of 2D shapes and bitmap images.
It is a low level, procedural model that updates a bitmap and does not have a
built-in scene. There are several methods in canvas to draw paths, boxes, circles,
text and add images.

How to create a HTML canvas?


A canvas is a rectangle like area on an HTML page. It is specified with canvas
element. By default, the <canvas> element has no border and no content, it is
like a container.
<canvas id = "mycanvas" width ="200" height ="100"> </canvas>
HTML 5 Canvas Tag Example
<canvas id="myCanvas1" width="300" height="100" style="border:2px
solid;">
Your browser does not support the HTML5 canvas tag.
</canvas>

Output:
HTML Canvas Tag with JavaScript
A canvas is a two dimensional grid.
Coordinates (0,0) defines the upper left corner of the canvas. The parameters
(0,0,200,100) is used for fillRect() method. This parameter will fill the rectangle
start with the upper-left corner (0,0) and draw a 200 * 100 rectangle.
1. <canvas id="myCanvas" width="250" height="150" style="border:1px s
olid #c3c3c3;">
2. Your browser does not support the HTML5 canvas tag.
3. </canvas>
4. <script>
5. var c = document.getElementById("myCanvas");
6. var cctx = c.getContext("2d");
7. ctx.fillStyle = "#FF0000";
8. ctx.fillRect(0,0,200,100);
9. </script>

Output:

Drawing Line on Canvas


If you want to draw a straight line on the canvas, you can use the following two
methods.
moveTo(x,y): It is used to define the starting point of the line.
lineTo(x,y): It is used to define the ending point of the line.
If you draw a line which starting point is (0,0) and the end point is (200,100), use
the stroke method to draw the line.
1. <canvas id="myCanvasLine" width="200" height="100" style="border:1
px solid #d3d3d3;">
2. Your browser does not support the HTML5 canvas tag.</canvas>
3. <script>
4. var c = document.getElementById("myCanvasLine");
5. var cctx = c.getContext("2d");
6. ctx.moveTo(0,0);
7. ctx.lineTo(200,100);
8. ctx.stroke();
9. </script>

Drawing Circle on Canvas


If you want to draw a circle on the canvas, you can use the arc() method:
1. arc(x, y, r, start, stop)
To sketch circle on HTML canvas, use one of the ink() methods, like stroke() or
fill().
1. <canvas id="myCanvasCircle" width="200" height="100" style="border:
1px solid #d3d3d3;">
2. Your browser does not support the HTML5 canvas tag.</canvas>
3. <script>
4. var c = document.getElementById("myCanvasCircle");
5. var cctx = c.getContext("2d");
6. ctx.beginPath();
7. ctx.arc(95,50,40,0,2*Math.PI);
8. ctx.stroke();
9. </script>

Drawing text on canvas


There are property and methods used for drawing text on the canvas.
font property: It is used to define the font property for the text.
fillText(text,x,y) method: It is used to draw filled text on the canvas. It looks
like bold font.
strokeText(text,x,y) method: It is also used to draw text on the canvas, but
the text is unfilled.
Let's see fillText() method example.
1. <canvas id="myCanvasText1" width="300" height="100" style="border:
1px solid #d3d3d3;">
2. Sorry! Your browser does not support the HTML5 canvas tag.</canvas>
3. <script>
4. var c = document.getElementById("myCanvasText1");
5. var cctx = c.getContext("2d");
6. ctx.font = "30px Arial";
7. ctx.fillText("Hello JavaTpoint",10,50);
8. </script>

1. ctx.strokeText("Hello JavaTpoint",10,50);

HTML <audio> Tag


The <audio> tag is used to embed sound content in a document, such as music
or other audio streams.
The <audio> tag contains one or more <source> tags with different audio
sources. The browser will choose the first source it supports.
The text between the <audio> and </audio> tags will only be displayed in
browsers that do not support the <audio> element.
There are three supported audio formats in HTML: MP3, WAV, and OGG.

Attributes
Attribute Value Description

autoplay autoplay Specifies that the audio will start playing as soon as it is
ready

controls controls Specifies that audio controls should be displayed (such


as a play/pause button etc)

loop loop Specifies that the audio will start over again, every time
it is finished

muted muted Specifies that the audio output should be muted

preload auto Specifies if and how the author thinks the audio should
metadata be loaded when the page loads
none

src URL Specifies the URL of the audio file

Example
<audio controls>
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio tag.
</audio>

HTML <video> Tag


The <video> tag is used to embed video content in a document, such as a movie
clip or other video streams.
The <video> tag contains one or more <source> tags with different video
sources. The browser will choose the first source it supports.
The text between the <video> and </video> tags will only be displayed in
browsers that do not support the <video> element.
There are three supported video formats in HTML: MP4, WebM, and OGG.
Optional Attributes
Attribute Value Description

autoplay autoplay Specifies that the video will start playing as soon as it is
ready

controls controls Specifies that video controls should be displayed (such


as a play/pause button etc).

height pixels Sets the height of the video player

loop loop Specifies that the video will start over again, every time
it is finished

muted muted Specifies that the audio output of the video should be
muted

poster URL Specifies an image to be shown while the video is


downloading, or until the user hits the play button

preload auto Specifies if and how the author thinks the video should
metadata be loaded when the page loads
none

src URL Specifies the URL of the video file

width pixels Sets the width of the video player

Example
<video width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>

HTML Drag and Drop


HTML Drag and Drop (DnD) is a feature of HTML5. It is a powerful user
interface concept which is used to copy, reorder and delete items with the help
of mouse. You can hold the mouse button down over an element and drag it to
another location. If you want to drop the element there, just release the mouse
button.
If you want to achieve the Drag and Drop functionality in traditional HTML4, you
must either have to use complex JavaScript programming or other JavaScript
frameworks like jQuery etc.

Events for Drag and Drop feature

Event Description

Drag It fires every time when the mouse is moved while the object is being dragged

Dragstart It is a very initial stage. It fires when the user starts dragging object.

Dragenter It fires when the user moves his/her mouse cursur over the target element.

Dragover This event is fired when the mouse moves over an element.

Dragleave This event is fired when the mouse leaves an element.

Drop Drop It fires at the end of the drag operation.

Dragend It fires when user releases the mouse button to complete the drag operation.

HTML5 Drag and Drop Example


Let's see an example of HTML 5 drag and drop feature.
To understand this example, you must have the knowledge of JavaScript.
1. <script>
2. function allowDrop(ev) {ev.preventDefault();}
3. function drag(ev) {ev.dataTransfer.setData("text/html", ev.target.id);}
4. function drop(ev) {
5. ev.preventDefault();
6. var data = ev.dataTransfer.getData("text/html");
7. ev.target.appendChild(document.getElementById(data));
8. }
9. </script>
10.<p>Drag the javatpoint image into the rectangle:</p>
11.<div id="div1" style="width:350px;height:100px;padding:10px;border:1p
x solid #aaaaaa;" ondrop="drop(event)" ondragover="allowDrop(event)"
></div>
12.<br>
13.<img id="drag1" src="/htmlpages/images/javatpoint.png" alt="javatpoint
image"
draggable="true" ondragstart="drag(event)"/>
In the above example, we have used ondrop and ondragover events on
div element, and ondragstart event on img tag.

Stages during Drag and Drop operations


1) Make an element draggable
If you want to make an element draggable, set the draggable attribute to "true"
on the element. For example:
1. <img draggable = "true">
2) What to drag:
Use ondragstart and setData () methods.
Specify what should happen when the element is dragged.
3) Where to Drop:
Use ondragover event.
4) Do the Drop:
Use ondrop event.

HTML5 Geolocation
The Geolocation is one of the best HTML5 API which is used to identify the user's
geographic location for the web application.
This new feature of HTML5 allows you to navigate the latitude and longitude
coordinates of the current website's visitor. These coordinates can be captured
by JavaScript and send to the server which can show your current location on the
website
Most of the geolocation services use Network routing addresses such as IP
addresses, RFID, WIFI
User privacy:
The user's location is the privacy concern, so geolocation API protects the user's
privacy by taking the user's permission before getting the location. Geolocation
API sends a notification prompt box which user can allow or deny, and if the user
allows then only his location will be identified.
Geolocation object
The Geolocation API is work with the navigation.geolocation object. Its read-only
property returns a Geolocation object which identifies the location of the user
and can generate a customized result based on user location.
Syntax:
1. geo=navigator. geolocation;
If this object is present, then you can get the geolocation services.
Geolocation Methods
The Geolocation API uses three methods of Geolocation interface which are given
following:

Methods Description

It identifies the device or the user's current


getCurrentPosition() location and returns a position object with
data.

Return a value whenever the device


watchPosition()
location changes.

clearWatch() It cancels the previous watchPosition() call

Checking for browser support:


The geolocation property of navigator.geolcation object helps to determine the
browser support for the Geolocation API.
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Geolocation API</title>
5. </head>
6. <body>
7. <h1>Find your Current location</h1>
8. <button onclick="getlocation()">Click me</button>
9. <div id="location"></div>
10.<script>
11. var x= document.getElementById("location");

12. function getlocation() {


13. if(navigator.geolocation){
14. alert("your browser is supporting Geolocation API")
15. }
16. else
17. {
18. alert("Sorry! your browser is not supporting")
19. }
20. }
21.</script>
22.</body>
23.</html>
Getting the User's current position:
To get the user's current location, getCurrentPosition() method of the
navigator.geolocation object is used. This method accepts three parameters:
o success: A success callback function to get the location of the user

o error: An error callback function which takes "Position Error" object as


input.
o options: It defines various options for getting the location.

The below example will return the longitude and latitude of the visitor's current
location.
Example
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Geolocation API</title>
5. </head>
6. <body>
7. <h1>Find your Current location</h1>
8. <button onclick="getlocation()">Click me</button>
9. <div id="location"></div>
10.<script>
11. var x= document.getElementById("location");
12. function getlocation() {
13. if(navigator.geolocation){
14. navigator.geolocation.getCurrentPosition(showPosition)
15. }
16. else
17. {
18. alert("Sorry! your browser is not supporting")
19. }}
20.
21. function showPosition(position){
22. var x = "Your current location is (" + "Latitude: " + position.coords.lati
tude + ", " + "Longitude: " + position.coords.longitude + ")";
23. document.getElementById("location").innerHTML = x;
24. }
25.</script>
26.</body>
27.</html>
Explanation:
o First checking the browser support

o Getting current position with getCurrentPosition()

o Getting latitude and longitude values with showPosition() method which is


call back method of getCurrentPosition().
Handling Errors and Rejections: Using an Error callback function
The second parameter of getCurrentPosition is an error Callback function. It is an
optional parameter and used to handle errors and user rejection while getting
the user's location.
Following are the possible options for invoking the error call back function:
o Unknown random error Occurred

o If the user has denied for sharing location

o Location information is not available


o Request for location is timed-out.

Example
1. function showError(error) {
2. switch(error.code){
3. case error.PERMISSION_DENIED:
4. alert("User denied the request for Geolocation API.");
5. break;
6. case error.POSITION_UNAVAILABLE:
7. alert("USer location information is unavailable.");
8. break;
9. case error.TIMEOUT:
10. alert("The request to get user location timed out.");
11. break;
12. case error.UNKNOWN_ERROR:
13. alert("An unknown error occurred.");
14. break;
15. }
16. }
Displaying location on Google Map
Till now, we have seen how to show your location using latitude and longitude
values, but it is not sufficient. Hence we can also show the exact location on
Google map with this API.
Following example showing the location using Google Map.
Example
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Geolocation API</title>
5. </head>
6. <body>
7. <h2>Find Your Location in below Map</h2>
8. <button onclick="getlocation();"> Show Position</button>
9. <div id="demo" style="width: 600px; height: 400px; margin-left: 200
px;"></div>
10.
11. <script src="https://maps.google.com/maps/api/js?sensor=false"> <
/script>
12.
13. <script type="text/javascript">
14. function getlocation(){
15. if(navigator.geolocation){
16. navigator.geolocation.getCurrentPosition(showPos, showErr);
17. }
18. else{
19. alert("Sorry! your Browser does not support Geolocation API")
20. }
21. }
22. //Showing Current Poistion on Google Map
23. function showPos(position){
24. latt = position.coords.latitude;
25. long = position.coords.longitude;
26. var lattlong = new google.maps.LatLng(latt, long);
27. var myOptions = {
28. center: lattlong,
29. zoom: 15,
30. mapTypeControl: true,
31. navigationControlOptions: {style:google.maps.NavigationControl
Style.SMALL}
32. }
33. var maps = new google.maps.Map(document.getElementById("de
mo"), myOptions);
34. var markers =
35. new google.maps.Marker({position:lattlong, map:maps, title:"You a
re here!"});
36. }
37. //Handling Error and Rejection
38. function showErr(error) {
39. switch(error.code){
40. case error.PERMISSION_DENIED:
41. alert("User denied the request for Geolocation API.");
42. break;
43. case error.POSITION_UNAVAILABLE:
44. alert("USer location information is unavailable.");
45. break;
46. case error.TIMEOUT:
47. alert("The request to get user location timed out.");
48. break;
49. case error.UNKNOWN_ERROR:
50. alert("An unknown error occurred.");
51. break;
52. }
53. } </script>
54. </body>
55.</html>
Location properties
The getCurrentPosition() method of Geolocation API returns callback methods
which retrieve the user location information. This callback method returns a
Position Object which contains all location information and specifies different
properties. It always returns latitude and longitude properties, but the following
table describes some other properties of Position object.

Properties Description

It returns latitude of user location as a


coords.latitude
decimal number.

It returns longitude of user location as


coords.longitude
a decimal number.

It returns altitude in meters above the


coords.altitude
sea level (Only if available).
It returns the accuracy of the user's
coords.accuracy
position.

It returns the altitude accuracy of user


coords.altitudeAccuracy
location. (If available)

It returns headings as degree


coords.heading
clockwise from North. (If available)

It returns the speed in meter per


coords.speed
seconds. (If available).

It returns data or time of response. (If


timestamp
available).

Watching the current location:


If we want to know the user location while he is moving and want accurate
location at every changed position, then it can be achieved by using
watchPosition() callback function.
This function has all three parameters which getCurrentPosition() contains.
Syntax:
1. var id = navigator.geolocation.watchPosition(success[, error[, options]])
The watchPosition() method returns an ID that can be used to uniquely
identifying the users position, and this ID can also be used with clearWatch()
method to stop watching the location.
Syntax:
1. navigator.geolocation.clearWatch(id);

Microdata
HTML Microdata is a form of semantic markup that provides additional
information about specific elements on a web page. This information is encoded
in the page's HTML code and can be used by search engines to better
understand the context and content of the page.
Microdata uses a set of standard properties and values, such
as itemprop and itemtype, to describe specific elements on a web page. Search
engines then use this information to provide more accurate search results,
improving the ranking of your website in search engines.
HTML Microdata works by adding additional information to the HTML code of a
web page. This information is encoded in the form of microdata properties and
values, which describe specific elements on the page.
For example, a web developer could use Microdata to provide information about
a product on an e-commerce website. This information could include the
product's name, price, and availability and be encoded as microdata properties
and values in the HTML code.
Once this information is added to the HTML code, search engines can use it to
provide more accurate and relevant information in search results, improving the
visibility and ranking of the website in search engines.
<div itemscope itemtype="http://schema.org/Product">
<h1 itemprop="name">Product Name</h1>
<span itemprop="price">$10.99</span>
<meta itemprop="availability" content="in_stock" />
</div>

Microdata Global Attributes


The Microdata Global Attributes in HTML5 are a set of attributes that allow web
developers to embed structured data into their HTML documents. The Microdata
Global Attributes include:

Attribute Description

itemsco This attribute specifies that the HTML5 element is a microdata item. By
pe using this attribute, you are indicating to search engines that the element
contains structured data that should be considered as a single unit.

itemtyp This attribute specifies the type of the microdata item, using a URL or a
e vocabulary-specific string. This information helps search engines
understand the context and content of the element and the type of
information it contains.

itemid This attribute specifies a unique microdata item identifier using a URL.
This identifier can reference the microdata item from other parts of the
web page or other web pages.

itempro This attribute specifies a property of the microdata item and associates it
p with the content of the HTML element. For example, you could use this
attribute to specify the author of a book or the date of an event.

itemref This attribute allows you to associate properties with a microdata item
that is located outside of the HTML5 element that has
the itemscope attribute

Browser
A web browser is an application used to access and interact with information on
the World Wide Web, such as web pages, videos, and images. The term
"browser" predates the web and referred to programs that allowed users to
navigate and read text files online.
Web browsers use HTTP to request information from web servers. While most
browsers support email and FTP, specialized programs are often used for these
tasks.
The first web browser, World Wide Web (later renamed Nexus), was created in
1990. Mosaic, the first browser with a graphical interface, launched in 1993,
influencing later browsers like Netscape Navigator and Internet Explorer.

Common Web Browser Features:


 Home button: Takes users to a pre-defined homepage.
 Address bar: Allows input of web addresses to visit websites.
 Back/forward buttons: Navigate to previous or next web pages.
 Refresh button: Reloads a web page.
 Stop button: Stops the page from loading.
 Tabs: Open multiple websites in one window.
 Bookmarks: Save favorite websites for quick access.
 Plug-ins: Extend browser functionality, such as adding security features.
How a Web Browser Works:
 Functions in a client/server model.
 The browser (client) requests data from the web server.
 It includes:
o User interface (UI) for user interaction.

o Browser engine to communicate with the rendering engine.

o Rendering engine to display web content (HTML, XML).

o Networking for internet communication and security.

o JavaScript interpreter for executing code.

o UI backend for creating windows and widgets.

o Persistence layer for managing data like bookmarks and cookies.

Popular Web Browsers:


 Google Chrome
 Mozilla Firefox
 Microsoft Edge
 Safari (Apple)
 Lynx (text-only for UNIX)
 Opera
 Flock (optimized for Web 2.0 features).

Browser lifecycle

The browser lifecycle refers to the sequence of steps a web browser goes
through to load, render, and manage web content. Here's a simplified breakdown
of the browser lifecycle:
1. Navigation/Request
 User Input: The user types a URL, clicks a link, or submits a form.
 Request Sent: The browser sends an HTTP request to the server hosting
the website.
2. Server Response
 Response Received: The server responds with the requested resources
(HTML, CSS, JavaScript, etc.).
 Status Code: The browser checks the HTTP status code (e.g., 200 for
success, 404 for not found).
3. Page Loading
 HTML Parsing: The browser starts parsing the HTML document.
 Resource Fetching: Additional resources (CSS, images, JavaScript files)
are fetched from the server or cache.
4. Rendering
 DOM Creation: The browser builds the Document Object Model (DOM)
from the HTML.
 CSSOM Creation: The browser constructs the CSS Object Model (CSSOM)
from the CSS.
 JavaScript Execution: JavaScript code is executed, modifying the DOM or
CSSOM as needed.
 Render Tree: The DOM and CSSOM combine to form a render tree,
defining how elements should appear on the page.
5. Layout
 Layout Calculation: The browser calculates the size, position, and
dimensions of each element based on the render tree.
6. Painting
 Visual Rendering: The browser converts the layout and styles into pixels
and renders them on the screen.
7. Interactivity
 User Interaction: The browser remains interactive, responding to user
actions like clicks, scrolls, and form inputs.
 JavaScript Handling: JavaScript can continuously modify the DOM and
respond to events, such as mouse clicks or key presses.
8. Reflow and Repaint (Dynamic Changes)
 Reflow: If the DOM or CSS is modified (e.g., by JavaScript), the browser
recalculates the layout of the affected elements (reflow).
 Repaint: The browser repaints the screen to reflect visual changes after
reflow or style updates.
9. Session Termination/Closure
 Page Unload: When the user navigates away or closes the browser tab,
the page unload event is triggered, and cleanup tasks like saving session
data or clearing resources occur.
This lifecycle repeats every time a user navigates to a new page or interacts with
the current one.

Browser rendering stages


The browser rendering process involves several key stages to transform HTML,
CSS, and JavaScript code into a visual representation on the screen. Below are
the main stages of the browser rendering process:
1. Parsing HTML and Building the DOM
 The browser receives the HTML file and starts parsing it.
 It builds the Document Object Model (DOM), a tree-like structure that
represents the elements and content of the HTML document.
2. Parsing CSS and Building the CSSOM
 The browser parses the CSS files linked in the HTML (or inline CSS).
 It constructs the CSS Object Model (CSSOM), another tree-like structure
representing the styles of the elements.
3. Combining DOM and CSSOM to Create the Render Tree
 The DOM and CSSOM are combined to create the render tree.
 The render tree includes only the visible elements on the page, ignoring
elements like <head> or those with display: none.
 Each node in the render tree contains the visual attributes (e.g., color,
size) required for painting the content on the screen.
4. Layout (Reflow)
 The browser calculates the exact position, size, and geometry of each
element on the page.
 This process is known as layout or reflow.
 The layout process considers the dimensions of the viewport (browser
window) and applies the CSS box model to calculate how elements are
displayed relative to each other.
5. Painting
 After the layout is complete, the browser proceeds to paint the render
tree.
 In this step, the browser converts elements into actual pixels, filling them
with colors, borders, text, images, and shadows according to the styles
defined in CSS.
6. Compositing
 The page may be divided into layers (e.g., for elements with position fixed
or absolute, or animations).
 Layers are individually painted and then combined in a process called
compositing.
 The browser's compositor takes these layers and arranges them in the
correct order to display the final page on the screen.
7. Rendering and Display
 Once compositing is complete, the browser renders the final page,
displaying it to the user.
 Throughout this process, JavaScript can dynamically modify the DOM and
CSSOM, which can trigger reflow or repaint if changes affect layout or
style.
Service workers
Service workers are a key feature in web development, enabling powerful
background functionality for web applications. They are JavaScript files that run
separately from the main browser thread, allowing web applications to handle
tasks even when the web page is not active.
Key Features of Service Workers:
 Background Functionality: Service workers run in the background,
enabling tasks like push notifications, background sync, and resource
preloading.
 Offline Support: Cache files and serve them without an internet
connection, providing offline functionality.
 Network Interception: Control how network requests are handled,
choosing between cache or network resources.
 Asynchronous: Operate independently of the main thread, ensuring
smooth user experiences.
How Service Workers Work:
1. Registration: Registered using navigator.serviceWorker.register() in
JavaScript.
2. Installation: Caches static assets (HTML, CSS, JS) during this phase.
3. Activation: Begins controlling pages and handling events once installed.
4. Caching/Fetching: Determines whether to retrieve resources from the
cache or network.
5. Lifecycle Management: Managed through install, activate, and fetch
events.
Benefits of Service Workers:
 Offline-first: Enables web apps to work without an internet connection.
 Performance: Reduces load times by caching frequently-used resources.
 Push Notifications: Allows notifications even when the app is closed.
 Background Sync: Syncs data in the background, ensuring actions (e.g.,
form submissions) complete while offline.
Example Code:
javascript
Copy code
self.addEventListener('install', event => {
event.waitUntil(
caches.open('my-cache').then(cache => {
return cache.addAll([
'/',
'/index.html',
'/styles.css',
'/script.js'
]);
})
);
});

self.addEventListener('fetch', event => {


event.respondWith(
caches.match(event.request).then(response => {
return response || fetch(event.request);
})
);
});

You might also like