HTML5 Interview Questions
HTML5 Interview Questions
by
www.questpond.com
(One stop place for .Net and C# interview question videos)
Contents
Introduction
I am ASP.NET MVC developer and recently when I was looking for a job lot of questions were
asked connected to HTML 5 and its new features. So below are 40 important questions which
would help you brush up your knowledge on HTML 5.
These questions are not silver bullet to get a job but yes they are helpful when you want to
quickly brush up the topic.
Courtesy: - www.questpond.com
What is the relationship between SGML, HTML , XML and HTML ?
SGML (Standard generalized markup language) is a standard which tells how to specify
document markup. It’s only a Meta language which describes how a document markup should
be. HTML is a markup language which is described using SGML.
So by SGML they created DTD which the HTML refers and needs to adhere to the same. So you
will always find “DOCTYPE” attribute at the top of HTML page which defines which DTD is
used for parsing purpose.
XHTML was created from XML which was used in HTML 4.0. So for example in SGML
derived HTML “</br>” is not valid but in XHTML it’s valid. You can refer XML DTD as shown
in the below code snippet.
In short SGML is the parent of every one. Older HTML utilizes SGML and HTML 4.0 uses
XHTML which derived from XML.
What is HTML 5?
HTML 5 is a new standard for HTML whose main target is to deliver everything without need to
any additional plugins like flash, Silverlight etc. It has everything from animations, videos, rich
GUI etc.
HTML5 is cooperation output between World Wide Web Consortium (W3C) and the Web
Hypertext Application Technology Working Group (WHATWG).
HTML 5 does not use SGML or XHTML it’s completely a new thing so you do not need to refer
DTD. For HTML 5 you just need to put the below doctype code which makes the browser
identify that this is a HTML 5 document.
<!DOCTYPE html>
No, browser will not be able to identify that it’s a HTML document and HTML 5 tags will not
function properly.
Almost all browsers i.e. Safari, Chrome, Firefox, Opera, Internet Explorer support HTML 5.
A typical web page has headers, footers, navigation, central area and side bars. Now if we want
to represent the same in HTML 4 with proper names to the HTML section we would probably
use a DIV tag.
But in HTML 5 they have made it more clear by creating element names for those sections which
makes your HTML more readable.
Below are more details of the HTML 5 elements which form the page structure.
Datalist element in HTML 5 helps to provide autocomplete feature in a textbox as shown below.
<input list="Country">
<datalist id="Country">
<option value="India">
<option value="Italy">
<option value="Iran">
<option value="Israel">
<option value="Indonesia">
</datalist>
1. Color.
2. Date
3. Datetime-local
4. Email
5. Time
6. Url
7. Range
8. Telephone
9. Number
10. Search
For URL validation set the type as “url” as shown in the below HTML code.
For URL validation set the type as “url” as shown in the below HTML code.
If you want to display textbox with number range you can set type to number.
If you want to display a range control you can use type as range.
<input type="range" min="0" max="10" step="2" value="6">
Output element is needed when you need calculation from two inputs to be summarized in to a
label. For instance you have two textboxes ( see the below figure) and you want to add numbers
from these textboxes and send them to a label.
Below goes the code of how to use output element with HTML 5.
You can also replace “parseInt” with “valueAsNumber” for simplicity. You can also use “for” in
the output element for more readability.
<output name="o" for="a b"></output>
What is SVG?
SVG stands for scalable vector graphics. It’s a text based graphic language which draws images
using text, lines, dots etc. This makes it lightweight and renders faster.
Let’s say we want to display the below simple line using HTML 5 SVG.
Below is how the code of HTML 5. You can see the SVG tag which encloses the polygon tag for
displaying the star image.
To draw on the canvas area we need to first get reference of the context section. Below is the
code for canvas section.
var c=document.getElementById("mycanvas");
var ctx=c.getContext("2d");
Now once you have access to the context object we can start drawing on the context. So first call
the “move” method and start from a point , use line method and draw the line and then apply
stroke over it.
ctx.moveTo(10,10);
ctx.lineTo(200,100);
ctx.stroke();
Below is the complete code.
<body onload="DrawMe();">
<canvas id="mycanvas" width="600" height="500" style="border:1px solid
#000000;"></canvas>
</body>
<script>
function DrawMe()
{
var c=document.getElementById("mycanvas");
var ctx=c.getContext("2d");
ctx.moveTo(10,10);
ctx.lineTo(200,100);
ctx.stroke();
}
You should get the below output.
Note :- If you see the previous two questions both canvas and SVG can draw
graphics on the browser. So in this question interviewer wants to know when
will you use what.
SVG Canvas
Here’s it’s like draw and remember. In other words any Canvas is like draw and forget. Once something is
shape drawn by using SVG can be remembered and drawn you cannot access that pixel and manipulate it.
manipulated and browser can render it again.
SVG is good for creating graphics like CAD software’s Canvas is good for draw and forget scenarios like
where once something is drawn the user wants to animation and games.
manipulate it.
This is slow as it needs to remember the co-ordinates for This is faster as there is no intention of remembering
later manipulations. things later.
We can have event handler associated with the drawing Here we cannot associate event handlers with drawing
object. objects as we do not have reference of them.
Resolution independent. Resolution dependent.
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();
<!DOCTYPE html>
<html>
<body onload="DrawMe();">
<svg width="500" height="100">
<circle id="circle1" cx="20" cy="20" r="10"
style="stroke: none; fill: #ff0000;"/>
</svg>
</body>
<script>
function DrawMe()
{
var circle = document.getElementById("circle1");
var x = circle.getAttribute("cx");
var newX = 2 + parseInt(x);
if(newX > 500)
{
newX = 20;
}
circle.setAttribute("cx", newX);
}
</script>
</html>
Selectors help to select an element to which you want to apply a style. For example below is a
simple style called as ‘intro” which applies red color to background of a HTML element.
<style>
.intro
{
background-color:red;
}
</style>
To apply the above “intro” style to div we can use the “class” selector as shown in the below
figure.
<div class="intro">
<p>My name is Shivprasad koirala.</p>
<p>I write interview questions.</p>
</div>
So let’s say you have a HTML paragraph tag with id “mytext” as shown in the below snippet.
You can create a style using “#” selector with the “id” name and apply the CSS value to the
paragraph tag. So to apply style to “mytext” element we can use “#mytext” as shown in the
below CSS code.
<style>
#mytext
{
background-color:yellow;
}
</style>
P,h1
{
background-color:yellow;
}
div p
{
background-color:yellow;
}
a[target]
{
background-color:yellow;
}
input:focus
{
background-color:yellow;
}
a:link {color:green;}
a:visited {color:green;}
a:hover {color:red;}
a:active {color:yellow;}
CSS column layout helps you to divide your text in to columns. For example consider the below
magazine news which is one big text but we need to divide the same in to 3 columns with a
border in between. That’s where HTML 5 column layout comes to help.
To implement column layout we need to specify the following:-
-moz-column-count:3; /* Firefox */
-webkit-column-count:3; /* Safari and Chrome */
column-count:3;
-moz-column-gap:40px; /* Firefox */
-webkit-column-gap:40px; /* Safari and Chrome */
column-gap:20px;
Do you want to draw a line between those columns , if yes how much thick ?
-moz-column-gap:40px; /* Firefox */
-webkit-column-gap:40px; /* Safari and Chrome */
column-gap:20px;
You can then apply the style to the text by using the class attribute.
<div class="magazine">
</div>
CSS box model is a rectangular space around a HTML element which defines border, padding
and margin.
Border: - This defines the maximum area in which the element will be contained. We can make
the border visible, invisible, define height and width etc.
For instance below is a simple CSS code which defines a box with border , padding and margin
values.
.box {
width: 200px;
border: 10px solid #99c;
padding: 20px;
margin: 50px;
}
Now if we apply the above CSS to a DIV tag as shown in the below code , your output would be
as shown in the figure below. I have created two test “Some text” and “Some other text” so that
we can see how margin property functions.
Here the interviewer is expecting you to answer one of two text effects by CSS. Below are two
effects which are worth noting.
.specialtext
{
text-shadow: 5px 5px 5px #FF0000;
}
<style>
.breakword
{word-wrap:break-word;}
</style>
What are web workers and why do we need them ?
Consider the below heavy for loop code which runs above million times.
function SomeHeavyFunction()
{
for (i = 0; i < 10000000000000; i++)
{
x = i + x;
}
}
Let’s say the above for loop code is executed on a HTML button click. Now this method
execution is synchronous. In other words the complete browser will wait until the for loop
completes.
This can further lead to browser getting freezed and unresponsive with an error message as
shown in the screen below.
So if we can move this heavy for loop in a JavaScript file and run it asynchronously that means
the browser does need to wait for the loop then we can have a more responsive browser. That’s
what web worker are for.
Web worker threads cannot modify HTML elements, global variables and some window
properties like Window.Location. You are free to use javascript data types, XMLHttpRequest
calls etc.
To create a worker thread we need to pass the JavaScript file name and create the worker object.
To send message to the worker object we need to use “PostMessage” , below is the code for the
same.
worker.postMessage();
When the worker thread sends data we get it in the “OnMessage” event on the callers end.
The heavy loop is in the “MyHeavyProcess.js” javascript file , below is the code for the same.
When the JavaScript file wants to send message he uses “postmessage” and any message sent
from the caller is received in the “onmessage” event.
var x =0
self.onmessage = function (e) {
for (i = 0; i < 1000000000; i++)
{
x = i + x;
}
self.postMessage(x);
};
w.terminate();
One of the common requirements in web world is getting updates from the server. Take example
of a stock ticker application where the browser has to take regular updates from the server for the
recent stock value.
Now to implement this kind of requirement developers normally write some kind of PULL code
which goes to the server and fetches data in certain interval. Now PULL solution is good but it
makes the network chatty with lot of calls and also it adds load on the server.
So rather than PULL it would be great if we can have some kind of PUSH solution. In simple
words when the server has updates it will send updates to the browser client. That can be
achieved by using “SERVER SENT EVENTS”.
So the first thing the browser needs to do is connect to the server source which will send updates.
Let’s say we have page “stock.aspx” which sends stock updates. So to connect to the page we
need to use attach to the event source object as shown in the below code.
Now from the server side we need to send events. Below are some lists of important events with
command that needs to be sent from the server side.
Event Command
Send data to the client. data : hello
Tell client to retry in 10 retry : 10000
seconds
Raise a specific event with event : success
data data : You are logged in.
So for example if we want to send data below is the ASP.NET code for the same. Please note the content type is set
to text/event.
Response.ContentType="text/event-stream";
Response.Expires=-1;
Response.Write("data: " + DateTime.Now.ToString());
Response.Flush();
Response.Write("retry: 10000");
If you want to attach an event we need to use the “addEventListener” event as shown in the
below code.
source.addEventListener('message', function(e) {
console.log(e.data);
}, false);
From the server side the below message will trigger the “message” function of javascript.
event: message
data : hello
Many times we would like to store information about the user locally in the computer. For
example let’s say user has half-filled a long form and suddenly the internet connection breaks
off. So the user would like you to store this information locally and when the internet comes
back.He would like to get that information and send it to the server for storage.
Modern browsers have storage called as “Local storage” in which you can store this information.
Data is added to local storage using “key” and “value”. Below sample code shows country data
“India” added with key value “Key001”.
localStorage.setItem(“Key001”,”India”);
To retrieve data from local storage we need to use “getItem” providing the key name.
You can also store JavaScript object’s in the local storage using the below code.
If you want to store in JSON format you can use “JSON.stringify” function as shown in the
below code.
localStorage.setItem(“I001”,JSON.stringify(country));
Session storage is same like local storage but the data is valid for a session. In simple words the
data is deleted as soon as you close the browser.
To create a session storage you need to use “sessionStorage.variablename” . In the below code
we have a created a variable called as “clickcount”.
If you refresh the browser the count increases. But if you close the browser and start again the
“clickcount” variable starts from zero.
if(sessionStorage.clickcount)
{
sessionStorage.clickcount=Number(sessionStorage.clickcount)+1;
}
else
{
sessionStorage.clickcount = 0;
}
Local storage data persists forever but session storage is valid until the browser is open, as soon
as the browser closes the session variable resets.
What is WebSQL?
WebSQL is a structured relational database at the client browser side. It’s a local RDBMS inside
the browser on which you can fire SQL queries.
No, many people label it as HTML 5 but it’s not part of HTML 5 specification. The specification
is based around SQLite.
The first step we need to do is open the database by using “OpenDatabase” function as shown
below. The first argument is the name of the database, the next is the version, then a simple
textual title and finally the size of the database.
db.transaction(function (tx)
{
tx.executeSql('CREATE TABLE IF NOT EXISTS tblCust(id unique,
customername)');
tx.executeSql('INSERT INTO tblcust (id, customername) VALUES(1, "shiv")');
tx.executeSql('INSERT INTO tblcust (id, customername) VALUES (2, "raju")');
}
In case you are firing “select” query you will get data is “results” collection which we can loop
and display in the HTML UI.
db.transaction(function (tx)
{
tx.executeSql('SELECT * FROM tblcust', [], function (tx, results) {
for (i = 0; i < len; i++)
{
msg = "<p><b>" + results.rows.item(i).log + "</b></p>";
document.querySelector('#customer).innerHTML += msg;
}
}, null);
});
One of the most demanded things by end user is offline browsing. In other words if internet
connection is not available page should come from browser cache i.e. offline and application
cache helps you to achieve the same.
Application cache helps you to specify which files should be cached and not cached.
The first thing in we need to specify is the “manifest” file. “manifest” file helps you to define
how your caching should work. Below is the structure of the manifest file :-
CACHE MANIFEST
# version 1.0
CACHE :
Login.aspx
Below is how cache manifest has been provided using ASP.NET C#.
Response.ContentType = "text/cache-manifest";
Response.Write("CACHE MANIFEST \n");
Response.Write("# 2012-02-21 v1.0.0 \n");
Response.Write("CACHE : \n");
Response.Write("Login.aspx \n");
Response.Flush();
Response.End();
One the cache manifest file is created the next thing is to provide the link of the manifest file in
the HTML page as shown below.
<html manifest="cache.aspx">
When the above file runs first time it gets added in the browser application cache and in case
server goes down the page is served from the application cache.
Application cache is removed by changing version number to a new version number as specified
in the “#” tag in the below code.
CACHE MANIFEST
# version 2.0(new)
CACHE :
Login.aspx
Aboutus.aspx
NETWORK :
Pages.aspx
Fallback in application cache helps you to specify the file which will displayed if the server is
not reachable. For instance in the below manifest file we are saying if someone hits “/home” and
if the server is not reachable then “homeoffline.html” file should be served.
FALLBACK:
/home/ /homeoffline.html
Network command says files which should not be cached. For example in the below code we are
saying that “home.aspx” should never be cached and or available offline.
NETWORK:
home.aspx