Anda di halaman 1dari 37

Can a <section> contain <article> elements?

Can
an <article> contain <section>elements? Provide usage examples.
Hide answer

The answer to both questions is yes; i.e., a <section> can contain <article> elements, and
an <article> can contain <section> elements.
For example, a personal dashboard page might contain a <section> for social network interactions as
well as a <section> for the latest news articles, the latter of which could contain
several <article> elements.
Conversely, an <article> might contain a <section> at the end for reader comments.
Comment

Can a web page contain multiple <header> elements? What


about <footer>elements?
Hide answer

Yes to both. In fact, both the

<header>

and <footer> tags are designed to serve their respective

purposes in relation to whatever their parent section may be. So not only can the
page <body> contain a header and a footer, but so can every <article> and <section> element. In fact,
a <header> should be present for all of these, although a <footer> is not always necessary.
Comment

What are web workers?


Hide answer

Web workers at long last bring multi-threading to JavaScript.


A web worker is a script that runs in the background (i.e., in another thread) without the page needing
to wait for it to complete. The user can continue to interact with the page while the web worker runs in
the background. Workers utilize thread-like message passing to achieve parallelism.
Comment

How do you indicate the character set being used by an HTML5


document? How does this differ from older HTML standards?
Hide answer

In HTML5, the encoding used can be indicated with the


documents <head> element:

charset

attribute of a <meta> tag inside the

<!DOCTYPE html>
<html>
<head>
...
<meta charset="UTF-8">
...

</head>
...
</html>

This is a slightly simpler syntax from older HTML standards, which did not have the
For example, an HTML 4.01 document would use the <meta> tag as follows:

charset

attribute.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">


<html>
<head>
...
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
...
</head>
...
</html>

Comment

Write the code necessary to create a 300 pixel by 300 pixel <canvas>.
Within it, paint a blue 100 pixel by 100 pixel square with the top-left corner
of the square located 50 pixels from both the top and left edges of the
canvas.
Hide answer

Here is one simple implementation:


<canvas id="c" width="300" height="300"></canvas>

<script>
var canvas = document.getElementById( "c" );
var drawing_context = canvas.getContext( "2d" );
drawing_context.fillStyle = "blue";
drawing_context.fillRect( 50, 50, 100, 100 );
</script>

Comment

Discuss the differences between an HTML specification and a


browsersimplementation thereof.
Hide answer

HTML specifications such as HTML5 define a set of rules that a document must adhere to in order to
be valid according to that specification. In addition, a specification provides instructions on how a
browser must interpret and render such a document.
2

A browser is said to support a specification if it handles valid documents according to the rules of
the specification. As of yet, no browser supports all aspects of the HTML5 specification (although all
of the major browser support most of it), and as a result, it is necessary for the developer to confirm
whether the aspect they are making use of will be supported by all of the browsers on which they
hope to display their content. This is why cross-browser support continues to be a headache for
developers, despite the improved specificiations.
In addition, while HTML5 defines some rules to follow for an invalid HTML5 document (i.e., one that
contains syntactical errors), invalid documents may contain anything, and it is impossible for the
specification to handle all possibilities comprehensively. Thus, many decisions about how to handle
malformed documents are left up to the browser.
Comment

Briefly describe the correct usage of the following HTML5 semantic


elements: <header>, <article>, <section>, <footer>.
Hide answer

The <header> element is used to contain introductory and navigational information about a section of
the page. This can include the section heading, the authors name, time and date of publication, table
of contents, or other navigational information.
The <article> element is meant to house a self-contained composition that can logically be
independently recreated outside of the page without losing its meaining. Individual blog posts or
news stories are good examples.
The <section> element is a flexible container for holding content that shares a common informational
theme or purpose.
The <footer> element is used to hold information that should appear at the end of a section of content
and contain additional information about the section. Authors name, copyright information, and
related links are typical examples of such content.
Comment

Describe the relationship between the <header> and <h1> tags in HTML5.
Hide answer

In previous specifications of HTML, only one <h1> element was typically present on a page, used for
the heading of the entire page. HTML5 specifies that <h1> represents the top-level heading of a
section, whether that be the page <body>, or an <article> or <section> element. In fact,
every <header> element should at least contain an <h1>element. If there is no natural heading for the
section, it is a good indication it should not use an <article> or <section> tag.
Comment

What are some of the key new features in HTML5?


Hide answer

Key new features of HTML5 include:


3

Improved support for embedding graphics, audio, and video content via the
new <canvas>, <audio>, and <video> tags.
Extensions to the JavaScript API such as geolocation and drag-and-drop as well
for storage and caching.
Introduction of web workers.
Several new semantic tags were also added to complement the structural logic of modern web
applications. These include the <main>, <nav>, <article>, <section>, <header>, <footer>,
and <aside> tags.
New form controls, such as <calendar>, <date>, <time>, <email>, <url>, and <search>.
Comment

What were some of the key goals and motivations for the HTML5
specification?
Hide answer

HTML5 was designed to replace both HTML 4, XHTML, and the HTML DOM Level 2.
Major goals of the HTML specification were to:
Deliver rich content (graphics, movies, etc.) without the need for additional plugins (e.g.,
Flash).
Provide better semantic support for web page structure through the introduction of new
structural element tags.
Provide a stricter parsing standard to simplify error handling, ensure more consistent crossbrowser behavior, and simplify backward compatibility with documents written to older
standards.
Provide better cross-platform support (i.e., to work well whether running on a PC, Tablet, or
Smartphone).
Comment

Give a simple implementation of the <video> tag to embed a video stored


at http://www.example.com/amazing_video.mp4. Give the video a width of
640 pixels by 360 pixels. Provide the user with controls.
Hide answer

Here is one simple implementation:


<video src="http://www.example.com/amazing_video.mp4" width="640" height="360" controls></video>

Alternatively, the source file may be indicated with a separate


the <video> element, as in:

<source>

tag inside

<video width="640" height="360" controls>

<source src="http://www.example.com/amazing_video.mp4">
</video>

Comment

What is HTML5 Web Storage? Explain localStorage and sessionStorage.


Hide answer

With HTML5, web pages can store data locally within the users browser.
Earlier, this was done with cookies. However, Web Storage is more secure and faster. The data is not
included with every server request, but used ONLY when asked for.
The data is stored in name/value pairs, and a web page can only access data stored by itself. Unlike
cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.
The difference between localStorage and sessionStorage involves the lifetime and scope of the
storage.
Data stored through localStorage is permanent: it does not expire and remains stored on the users
computer until a web app deletes it or the user asks the browser to delete it. SessionStorage has the
same lifetime as the top-level window or browser tab in which the script that stored it is running.
When the window or tab is permanently closed, any data stored through sessionStorage is deleted.
Both forms of storage are scoped to the document origin so that documents with different origins will
never share the stored objects. But sessionStorage is also scoped on a per-window basis. If a user
has two browser tabs displaying documents from the same origin, those two tabs have separate
sessionStorage data: the scripts running in one tab cannot read or overwrite the data written by
scripts in the other tab, even if both tabs are visiting exactly the same page and are running exactly
the same scripts.
Comment

* There is more to interviewing than tricky technical questions, so these are intended merely as a guide. Not every
A candidate worth hiring will be able to answer them all, nor does answering them all guarantee an A candidate.
At the end of the day, hiring remains an art, a science and a lot of work.
http://www.toptal.com/html5/interview-questions

HTML5 Local Storage


5

Previous
Next Chapter

HTML local storage, better than cookies.

What is HTML Local Storage?


With local storage, web applications can store data locally within the user's browser.
Before HTML5, application data had to be stored in cookies, included in every server
request. Local storage is more secure, and large amounts of data can be stored locally,
without affecting website performance.
Unlike cookies, the storage limit is far larger (at least 5MB) and information is never
transferred to the server.
Local storage is per domain. All pages, from one domain, can store and access the same
data.

Browser Support
The numbers in the table specify the first browser version that fully supports Local Storage.
API

Web Storage

4.0

8.0

3.5

4.0

HTML Local Storage Objects


HTML local storage provides two objects for storing data on the client:
6

window.localStorage - stores data with no expiration date

window.sessionStorage - stores data for one session (data is lost when the tab is
closed)

Before using local storage, check browser support for localStorage and sessionStorage:
if(typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
} else {
// Sorry! No Web Storage support..
}

The localStorage Object


The localStorage object stores the data with no expiration date. The data will not be deleted
when the browser is closed, and will be available the next day, week, or year.

Example
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
Example explained:

Create a localStorage name/value pair with name="lastname" and value="Smith"

Retrieve the value of "lastname" and insert it into the element with id="result"

The example above could also be written like this:


// Store
localStorage.lastname = "Smith";
// Retrieve
document.getElementById("result").innerHTML = localStorage.lastname;

The syntax for removing the "lastname" localStorage item is as follows:


localStorage.removeItem("lastname");

Note: Name/value pairs are always stored as strings. Remember to convert them to another
format when needed!
The following example counts the number of times a user has clicked a button. In this code
the value string is converted to a number to be able to increase the counter:

Example
if (localStorage.clickcount) {
localStorage.clickcount = Number(localStorage.clickcount) + 1;
} else {
localStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
localStorage.clickcount + " time(s).";

The sessionStorage Object


The sessionStorage object is equal to the localStorage object, except that it stores the data
for only one session. The data is deleted when the user closes the browser window.
The following example counts the number of times a user has clicked a button, in the
current session:

Example
if (sessionStorage.clickcount) {
sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";

Contents
Introduction
What is the difference between Canvas and SVG graphics?
How to draw rectangle using Canvas and SVG using HTML 5 ?
8

What are selectors in CSS?


How can you apply CSS style using ID value?
What is the use of column layout in CSS?
Can you explain CSS box model?
Can you explain some text effects in CSS 3?
What are web workers and why do we need them ?
How can we add and remove data from local storage?
What is the lifetime of local storage?
What is the difference between local storage and cookies?
What is difference between session storage and local storage?
What is WebSQL?
Is WebSQL a part of HTML 5 specification?
So how can we use WebSQL ?
So how do we implement application cache in HTML 5 ?
What is fallback in Application cache?
References for other interview question articles

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.
Happy job hunting.

Courtesy: -www.questpond.com

What is the relationship between SGML,HTML ,


XML and XHTML?
SGML (Standard generalized markup language) is a standard which tells how to specify
document markup. Its 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.
Hide Copy Code

<!--!doctype-->

Now parsing SGML was a pain so they created XML to make things better. XML uses SGML. For
example in SGML you have to start and end tags but in XML you can have closing tags which
close automatically ().
XHTML was created from XML which was used in HTML 4.0. So for example in SGML derived
HTML
is not valid but in XHTML its valid. You can refer XML DTD as shown in the below code snippet.
Hide Copy Code

<!--!doctype--><!--!doctype-->

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.
10

HTML5 is cooperation output between World Wide Web Consortium (W3C) and the Web Hypertext
Application Technology Working Group (WHATWG).

If I do not put <! DOCTYPE html> will HTML 5


work?
No, browser will not be able to identify that its a HTML document and HTML 5 tags will not
function properly.

Which browsers support HTML 5?


Almost all browsers i.e. Safari, Chrome, Firefox, Opera, Internet Explorer support HTML 5.

How is the page structure of HTML 5 different


from HTML 4 or previous HTML?
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.

<header>: Represents header data of HTML.


<footer>: Footer section of the page.
<nav>: Navigation elements in the page.
<article>: Self-contained content.
<section>: Used inside article to define sections or group content in to sections.
<aside>: Represent side bar contents of a page.
11

What is datalist in HTML 5?


Datalist element in HTML 5 helps to provide autocomplete feature in a textbox as shown below.

Below is the HTML code for DataList feature:Hide Copy Code

<input list="Country">
<datalist id="Country">
<option value="India">
<option value="Italy">
<option value="Iran">
<option value="Israel">
<option value="Indonesia">
</datalist>

What are the different new form element types


in HTML 5?
There are 10 important new form elements introduced in HTML 5:1.
2.
3.
4.
5.
6.
7.
8.
9.
10.

Color.
Date
Datetime-local
Email
Time
Url
Range
Telephone
Number
Search

Lets understand these elements step by step.


If you want to show color picker dialog box.
Hide Copy Code

<input type="color" name="favcolor">

12

If you want to show calendar dialog box.


Hide Copy Code

<input type="date" name="bday">

If you want to show calendar with local time.


Hide Copy Code

<input type="datetime-local" name="bdaytime">

13

If you want to create a HTML text with email validation we can set the type as email.
Hide Copy Code

<input type="email" name="email">

For URL validation set the type as url as shown in the below HTML code.
Hide Copy Code

<input type="url" name="sitename">

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.
Hide Copy Code

<input type="number" name="quantity" min="1" max="5">

If you want to display a range control you can use type as range.
Hide Copy Code

<input type="range" min="0" max="10" step="2" value="6">

14

Want to make text box as search engine box.


Hide Copy Code

<input type="search" name="googleengine">

What to only take time input.


Hide Copy Code

<input type="time" name="usr_time">

If you want to make text box to accept telephone numbers.


Hide Copy Code

<input type="tel" name="mytel">

What is output element in HTML 5?


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.
Hide Copy Code

<form onsubmit="return false" &ouml;ninput="o.value = parseInt(a.value) + parseInt(b.value)">


<input name="a" type="number"> +
<input name="b" type="number"> =
<output name="o" />
</form>

You can also replace parseInt with valueAsNumber for simplicity. You can also use for in the
output element for more readability.
Hide Copy Code

<output name="o" for="a b"></output>

What is SVG?
SVG stands for scalable vector graphics. Its a text based graphic language which draws images
using text, lines, dots etc. This makes it lightweight and renders faster.

15

Can we see a simple example of SVG using


HTML 5?
Lets 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.
Hide Copy Code

<svg id="svgelem" height="[object SVGAnimatedLength]" xmlns="http://www.w3.org/2000/svg">


<line style="stroke: rgb(255, 0, 0); stroke-width: 2px;" y2="[object SVGAnimatedLength]" x2="[object
SVGAnimatedLength]" y1="[object SVGAnimatedLength]" x1="[object SVGAnimatedLength]">
</line>

What is canvas in HTML 5?


Canvas is an HTML area on which you can draw graphics.

<canvas height=""500"" id=""mycanvas"" soli


d=""style=""border:1px" width=""600""></can
vas>
Get access to canvas area
To draw on the canvas area we need to first get reference of the context section. Below is the code for
canvas section.
Hide Copy Code

var c=document.getElementById("mycanvas");
var ctx=c.getContext("2d");

Draw the graphic


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.
Hide Copy Code

16

<a name="WhatisthedifferencebetweenCanvasandSVGgraphics">What is the difference between Canvas and SVG


graphics? </a>

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.

Canvas

SVG
Heres its like draw and remember. In other words any shape
drawn by using SVG can be remembered and manipulated and
browser can render it again.
SVG is good for creating graphics like CAD softwares where once
something is drawn the user wants to manipulate it.
This is slow as it needs to remember the co-ordinates for later
manipulations.
We can have event handler associated with the drawing object.
Resolution independent.

Canvas is like draw and forget. Once som


cannot access that pixel and manipulate i

Canvas is good for draw and forget scena


games.

This is faster as there is no intention of re


Here we cannot associate event handlers
we do not have reference of them.
Resolution dependent.

How to draw rectangle using Canvas and SVG


using HTML 5?
HTML 5 code Rectangle code using SVG.
Hide Copy Code

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">


<rect style="fill: rgb(0, 0, 255); stroke-width: 1px; stroke: rgb(0, 0, 0);" height="[object SVGAnimatedLength]"
width="[object SVGAnimatedLength]">
</rect>

HTML 5 Rectangle code using canvas.


Hide Shrink

Copy Code

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.rect(20,20,150,100);
ctx.stroke();
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<circle fill="red" stroke-width="2" stroke="black" r="[object SVGAnimatedLength]" cy="[object
SVGAnimatedLength]" cx="[object SVGAnimatedLength]">
var
var
var
var
var

canvas = document.getElementById('myCanvas');
context = canvas.getContext('2d');
centerX = canvas.width / 2;
centerY = canvas.height / 2;
radius = 70;

context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();

17

context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();
<!DOCTYPE html>
<html>
<body &ouml;nload="DrawMe();">
<svg height="[object SVGAnimatedLength]" width="[object SVGAnimatedLength]">
<circle id="circle1" cx="[object SVGAnimatedLength]" cy="[object SVGAnimatedLength]" r="[object
SVGAnimatedLength]" style="stroke: none; fill: rgb(255, 0, 0);">
</body>
<script>
var timerFunction = setInterval(DrawMe, 20);
alert("ddd");
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></circle>

What are selectors in CSS?


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.
Hide Copy Code

<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.
Hide Copy Code

<div class="intro">
<p>My name is Shivprasad koirala.</p>
<p>I write interview questions.</p>
</div>

How can you apply CSS style using ID value?


So lets say you have a HTML paragraph tag with id mytext as shown in the below snippet.
18

Hide Copy Code

<p id="mytext">This is HTML interview questions.</p>

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.
Hide Copy Code

<style>
#mytext
{
background-color:yellow;
}
</style>

Quick revision of some important selectors.


Set all paragraph tags back ground color to yellow.
Hide Copy Code

P,h1
{
background-color:yellow;
}

Sets all paragraph tags inside div tag to yellow background.


Hide Copy Code

div p
{
background-color:yellow;
}

Sets all paragraph tags following div tags to yellow background.


Hide Copy Code

div+p
{
background-color:yellow;
}

Sets all attribute with target to yellow background.


Hide Copy Code

a[target]
{
background-color:yellow;
}
<a href="http://www.questpond.com">ASP.NET interview questions</a>
<a href="http://www.questpond.com" target="_blank">c# interview questions</a>
<a href="http://www.questpond.org" target="_top">.NET interview questions with answers</a>

Set all elements to yellow background when control gets focus.

19

Hide Copy Code

input:focus
{
background-color:yellow;
}

Set hyperlinks according to action on links.


Hide Copy Code

a:link {color:green;}
a:visited {color:green;}
a:hover {color:red;}
a:active {color:yellow;}

What is the use of column layout in CSS?


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. Thats where HTML 5 column layout comes to help.

To implement column layout we need to specify the following:

How many columns we want to divide the text in to ?


To specify number of columns we need to us column-count. webkit and moz-column are needed
for chrome and firefox respectively.
Hide Copy Code

-moz-column-count:3; /* Firefox */
-webkit-column-count:3; /* Safari and Chrome */
column-count:3;

How much gap we want to give between those columns ?


Hide Copy Code

-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 ?

20

Hide Copy Code

-moz-column-rule:4px outset #ff00ff; /* Firefox */


-webkit-column-rule:4px outset #ff00ff; /* Safari and Chrome */
column-rule:6px outset #ff00ff;

Below is the complete code for the same.


Hide Copy Code

<style>
.magazine
{
-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;
-moz-column-rule:4px outset #ff00ff; /* Firefox */
-webkit-column-rule:4px outset #ff00ff; /* Safari and Chrome */
column-rule:6px outset #ff00ff;
}
</style>

You can then apply the style to the text by using the class attribute.
Hide Copy Code

<div class="magazine">
Your text goes here which you want to divide in to 3 columns.
</div>

Can you explain CSS box model?


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.
Padding: - This defines the spacing between border and element.
Margin: - This defines the spacing between border and any neighboring elements.

21

For instance below is a simple CSS code which defines a box with border , padding and margin values.
Hide Copy Code

.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.
Hide Copy Code

<div align="middle" class="box">


Some text
</div>
Some other text

22

Can you explain some text effects in CSS 3?


Here the interviewer is expecting you to answer one of two text effects by CSS.Below are two effects
which are worth noting.
Shadow text effect
Hide Copy Code

.specialtext
{
text-shadow: 5px 5px 5px #FF0000;
}

Word wrap effect


Hide Copy Code

<style>
.breakword
{word-wrap:break-word;}
</style>

23

What are web workers and why do we need


them ?
Consider the below heavy for loop code which runs above million times.
Hide Copy Code

function SomeHeavyFunction()
{
for (i = 0; i < 10000000000000; i++)
{
x = i + x;
}
}

Lets 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.
Hide Copy Code

<input type="button" onclick="SomeHeavyFunction();" />

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. Thats what web
worker are for.

24

Web worker helps to execute JavaScript file asynchronously.

What is local storage concept in HTML 5?


Many times we would like to store information about the user locally in the computer. For example
lets 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.

How can we add and remove data from local


storage?
Data is added to local storage using key and value. Below sample code shows country data
India added with key value Key001.
Hide Copy Code

localStorage.setItem(&ldquo;Key001&rdquo;,&rdquo;India&rdquo;);

To retrieve data from local storage we need to use getItem providing the key name.
Hide Copy Code

var country = localStorage.getItem(&ldquo;Key001&rdquo;);

You can also store JavaScript objects in the local storage using the below code.
Hide Copy Code

var country = {};


country.name = &ldquo;India&rdquo;;
country.code = &ldquo;I001&rdquo;;
localStorage.setItem(&ldquo;I001&rdquo;, country);
var country1 = localStorage.getItem(&ldquo;I001&rdquo;);

If you want to store in JSON format you can use JSON.stringify function as shown in the below code.
Hide Copy Code

localStorage.setItem(&ldquo;I001&rdquo;,JSON.stringify(country));

What is the lifetime of local storage?


Local storage does not have a life time it will stay until either the user clear it from the browser or you
remove it using JavaScript code.

What is the difference between local storage


and cookies?
25

Cookies
Data accessible both at client side
Client side
and server side. Cookie data is sent
/ Server
to the server side with every
side.
request.
Size
4095 bytes per cookie.

Local storage
Data is accessible only at the local browser side.
Server cannot access local storage until
deliberately sent to the server via POST or GET.

5 MB per domain.
There is no expiration data. Either the end user
Cookies have expiration attached to
needs to delete it from the browser or
Expiration it. So after that expiration the cookie
programmatically using JavaScript we need to
and the cookie data gets deleted.
remove the same.

1. What are different ways to apply styles to a Web page?


There are four ways to apply style to a Web page.
26

A.

Inline CSS: HTML elements may have CSS applied to them via the STYLE
attribute.For Example: If You have <p> element into webpage, you can apply
inline style likeshows in example.<p style=font-size: 12px; color:
#000000;>Test </p>

You can always check HTML, CSS and JavaScript code impact using Online HTML
Javascript editor.
Embedded CSS: CSS may be embedded in a Web page by placing the code

in a STYLE element within the HEAD element.For Example: If You have <h2>
element into webpage, you can apply embedded style like shows in example.

<head>

<style type=text/css>
h2 {
font-size: 16px;
color: #2d2d2d;
font-weight: 900;
}
</style>

</head>
Linked CSS: CSS can be placed in an external file (a simple text file containing
CSS) and linked via the link element.You can apply style to webpage using external
file as shown in example.
<link rel=stylesheet href=custom/custom.css type=text/css media=screen,

projection />
Imported CSS: Another way to utilize external CSS files via @import.<style>
@import url(/css/styles.css);
</style>
Put then your styles.css document can contain calls to any number of additional
style sheets:
@import url(/css/typography.css);
@import url(/css/layout.css);
@import url(/css/color.css);

2. How do CSS precedence/cascading rules work? How does the !important


directive affect the rules?
27

CSS style rules cascade in the sense that they follow an order of precedence. Global style
rules apply first to HTML elements, and local style rules override them. For example, a style
defined in a style element in a webpage overrides a style defined in an external style sheet.
Similarly, an inline style that is defined in an HTML element in the page overrides any styles
that are defined for that same element elsewhere.
The !important rule is a way to make your CSS cascade but also have the rules you feel are
most crucial always be applied. A rule that has the !important property will always be
applied no matter where that rule appears in the CSS document. So if you wanted to make
sure that a property always applied, you would add the !important property to the tag. So,
to make the paragraph text always red, in the above example, you would write:
p { color: #ff0000 !important; }
p { color: #000000; }

3. What is a class? What is an ID?


A class is a style (i.e., a group of CSS attributes) that can be applied to one or more HTML
elements. This means it can apply to instances of the same element or instances of different
elements to which the same style can be attached. Classes are defined in CSS using a period
followed by the class name. It is applied to an HTML element via the class attribute and the
class name.
The following snippet shows a class defined, and then it being applied to an HTML DIV
element.
.test {font-family: Helvetica; font-size: 20; background: black;}
<div class =test><p>test</p></div>
Also, you could define a style for all elements with a defined class. This is demonstrated with
the following code that selects all P elements with the column class specified.
p.column {font-color: black;}
An ID selector is a name assigned to a specific style. In turn, it can be associated with one
HTML element with the assigned ID. Within CSS, ID selectors are defined with the #
character followed by the selector name.

28

The following snippet shows the CSS example1 defined followed by the use of an HTML
elements ID attribute, which pairs it with the CSS selector.
#example1: {background: blue;}
<div id=example1></div>
4. What is the difference between an ID selector and CLASS?
An ID selector identifies and sets style to only one occurrence of an element, while CLASS
can be attached to any number of elements.
5. What is Contextual Selector?
Contextual selector addresses specific occurrence of an element. It is a string of individual
selectors separated by white space (search pattern), where only the last element in the
pattern is addressed providing it matches the specified contex
6. What is Grouping?
When more than one selector shares the same declaration, they may be grouped together
via a comma-separated list; this allows you to reduce the size of the CSS (every bit and
byte is important) and makes it more readable. The following snippet applies the same
background to the first three heading elements.
h1, h2, h3 {background: red;}
7. What are Child Selectors?
A child selector is used when you want to match an element that is the child of another
specific element. The parent and child selectors are separated by spaces. The following
selector locates an unordered list element within a paragraph element and makes a text
within that element bold.
p > ul {font-weight: bold;}

8. What are Pseudo Classes?

29

Pseudo classes allow you to identify HTML elements on characteristics (as opposed to their
name or attributes). The classes are specified using a colon to separate the element name
and pseudo class. A good example is the :link and :visited pseudo classes for the HTML A
element. Another good example is first-child, which finds an elements first child element.
The following CSS makes all visited links red and green, the actual link text becomes yellow
when the mouse pointer is positioned over it, and the text of the first element of a
paragraph is bold.
a:link {font-color: red;}
a:visited {font-color: green;}
a:hover {font-color: yellow;}
p.first-child {font-weight: bold;}
10. Whats the difference between an inline element and a block element?
A block-level element is an element that creates large blocks of content like paragraphs or
page divisions. They start new lines of text when you use them, and can contain other
blocks as well as inline elements and text or data.
An inline element is an element that define text or data in the document like STRONG makes
the enclosed text strongly emphasized and Q says the enclosed text is a quotation. They
dont start new lines when you use them, and they generally only contain other inline tags
and text or data. Or they include nothing at all, like the BR tag.
Some properties that inline elements ignore include:

width and height

max-width and max-height

min-width and min-height

The CSS property display lets you change an inline property to block or a block to inline or
either of them to not display at all.
display: block;
display:inline;
display:none;

WHEN TO CHANGE THE DISPLAY PROPERTY

30

Horizontal list menus - Lists are block-level elements, but if you want your menu to
display horizontally, you need to convert the list to an inline element, so that newlines

arent added between each list item.


Headers in the text - Sometimes you might want a header to remain in the text, but
have the HTML header values. Changing the h1-h6 values to inline will let the following

text flow next to it.


Removing the element - And of course, if you want to remove the element
completely from the document flow, you can set the display to none.

11. Explain how the CSS box model works. Draw a box and then explain what the
border is, what the margin is, what the padding is, etc.? If you assign a width: or
height: to something, what specifically does that refer to?
All HTML elements can be considered as boxes. In CSS, the term box model is used when
talking about design and layout.
The CSS box model is essentially a box that wraps around HTML elements, and it consists
of: margins, borders, padding, and the actual content.
The box model allows us to place a border around elements and space elements in relation
to other elements.

Explanation of the different parts:

Margin - Clears an area around the border. The margin does not have a background
color, it is completely transparent
31

Border - A border that goes around the padding and content. The border is affected

by the background color of the box


Padding - Clears an area around the content. The padding is affected by the

background color of the box


Content - The content of the box, where text and images appear

Here is the snippet to draw box model to your web page.


<head>
<style>
div.test
{
width:220px;
padding:10px;
border:5px solid gray;
margin:0px;
}
</style>
</head>
<body>
<div class=test>The picture above is 250px wide. The total width of this element is

also

250px.</div>
</body>
12. Explain vertical margin collapsing.
Top and bottom margins of blocks are sometimes combined (collapsed) into a single margin
whose size is the largest of the margins combined into it, a behavior known as margin
collapsing.
Margin collapsing occurs in three basic cases:
Adjacent siblings
The margins of adjacent siblings are collapsed (except when the later sibling needs
to be cleared past floats).
32

Parent and first/last child


If there is no border, padding, inline content, or clearance to separate the margintop of a block with the margin-top of its first child block, or no border, padding, inline

content, height, min-height, or max-height to separate the margin-bottom of a block


with the margin-bottom of its last child, then those margins collapse. The collapsed
margin ends up outside the parent.
Empty blocks
If there is no border, padding, inline content, height, or min-height to separate a
blocks margin-top from its margin-bottom, then its top and bottom margins
collapse.
vertical margins collapse between certain boxes.
To understand how vertical margins collapse lets start with a basic html and CSS
example.
Adjacent Elements With Positive Margin
Vertical adjoining margins collapses. If two elements has positive vertically
adjoining margin than only the maximum of both will take effect.

CSS CODE

1
2
3

#parent{ background-color:yellow; width:300px; }


#red {background-color:red; height:50px; margin-bottom:30px;}
#blue {background-color:blue; height:50px; margin-top:20px;}

BRO WSER RE SU LT

33

Margins of floating and absolutely positioned elements never collapse.


There are other situations where elements do not have their margins collapsed:

inline-block elements

elements with overflow set to anything other than visible (They do not collapse

margins with their children.)


cleared elements (They do not collapse their top margins with their parent

blocks bottom margin.)


the root element

13. How do you float an element, and what does that mean? Whats Clearing?
With CSS float, an element can be pushed to the left or right, allowing other elements to
wrap around it.
Float is very often used for images, but it is also useful when working with layouts.
Elements are floated horizontally, this means that an element can only be floated left or
right, not up or down.
A floated element will move as far to the left or right as it can. Usually this means all the
way to the left or right of the containing element.
Below is the example, which shows using css float property you can set image to the right of
your web page.
<head>
<style>
img
{
float:right;
}
34

</style>
</head>
<body>
<p>
<img src=logocss.gif width=95 height=84 />
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
</p>
</body>
14. Whats the difference between position: relative, position: fixed & position:
absolute?
Here, Ive listed basic difference between css positioning properties.
Position-Relative. This type of positioning is probably the most confusing and misused.
What it really means is relative to itself. If you set position: relative;on an element but no
other positioning attributes (top, left, bottom or right), it will no effect on its positioning at
all, it will be exactly as it would be if you left it as position: static; But if you DO give it some
other positioning attribute, say, top: 10px;, it will shift its position 10 pixels DOWN from
where it would NORMALLY be.
Position-Absolute. This is a very powerful type of positioning that allows you to literally
place any page element exactly where you want it. You use the positioning attributes top,
left bottom and right to set the location. Remember that these values will be relative to the
next parent element. If there is no such parent, it will default all the way back up to the
<html> element itself meaning it will be placed relatively to the page itself.
35

Position-Fixed. This type of positioning is fairly rare but certainly has its uses. A fixed
position element is positioned relative to the viewport, or the browser window itself. The
viewport doesnt change when the window is scrolled, so a fixed positioned element will stay
right where it is when the page is scrolled.
15. What does z-index do?
The z-index property specifies the stack order of an element.
An element with greater stack order is always in front of an element with a lower stack
order.
Here is the Example, where using z-index property you can display in front of image.
<head>
<style>
img
{
position:absolute;
left:0px;
top:0px;
z-index:-1;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<img src=w3css.gif width=100 height=140 />
<p>Because the image has a z-index of -1, it will be placed behind the text.</p>
</body>
(4) Define and explain : what is CSS opacity and transparency? How it works?
You can use opacity property to make the original image displayed transparent / semi
transparent on your web page.
I have an example as to how you can use the property :

36

<style>
img {
opacity: 0.5;
filter: alpha(opacity=50); /* For IE8 and earlier */
}
</style>

37

Anda mungkin juga menyukai