html_interview_questions

HTML5 Interview Questions and Answers

Click if you like the project. Pull Request are highly appreciated.

Table of Contents

Q. Does localStorage throw error after reaches maximum limits?

Yes

Example:

<!DOCTYPE HTML>
<html>
   <head>
         <title>HTML5 localStorage</title>
   </head>
   <body>
      <script type="text/javascript">
        try{
            if(window.localStorage){ // Check if the localStorage object exists
            
                var result = "";
                var characters  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
                var charactersLength = characters.length;
                for(var i = 0; i < 10000; i++){
                    result += characters.charAt(Math.floor(Math.random() * charactersLength));
                    localStorage.setItem("key"+i, result);
                }  
            } else {
                alert("Sorry, your browser do not support localStorage.");
            }
        } catch(e) {
            console.log('Exception: '+e);
        }
      </script>
   </body>
</html>

Output

Exception: QuotaExceededError: Failed to execute 'setItem' on 'Storage': 
           Setting the value of 'key3230' exceeded the quota.
↥ back to top

Q. What is the DOM? How does the DOM work?

The DOM (Document Object Model) is a cross-platform API that treats HTML documents as a tree structure consisting of nodes. These nodes (such as elements and text nodes) are objects that can be programmatically manipulated and any visible changes made to them are reflected live in the document. In a browser, this API is available to JavaScript where DOM nodes can be manipulated to change their styles, contents, placement in the document, or interacted with through event listeners.

Q. How does the browser rendering engine work?

In order to render content the browser has to go through a series of steps:

Browser Rendering Engine

↥ back to top

Q. What does a <DOCTYPE html> do?

A DOCTYPE is always associated to a DTD ( Document Type Definition ). A DTD defines how documents of a certain type should be structured (i.e. a button can contain a span but not a div), whereas a DOCTYPE declares what DTD a document supposedly respects (i.e. this document respects the HTML DTD). For webpages, the DOCTYPE declaration is required. It is used to tell user agents what version of the HTML specifications your document respects.

Once a user agent has recognized a correct DOCTYPE, it will trigger the no-quirks mode matching this DOCTYPE forreading the document. If a user agent doesn’t recognize a correct DOCTYPE, it will trigger the quirks mode.

Q. What happens when DOCTYPE is not given?

The web page is rendered in quirks mode. The web browsers engines use quirks mode to support older browsers which does not follow the W3C specifications. In quirks mode CSS class and id names are case insensitive. In standards mode they are case sensitive.

↥ back to top

Q. What is the difference between standards mode and quirks mode?

In Quirks mode, layout emulates nonstandard behavior in Navigator 4 and Internet Explorer 5. This is essential in order to support websites that were built before the widespread adoption of web standards. In Standards mode, the behavior is described by the HTML and CSS specifications.

For HTML documents, browsers use a <!DOCTYPE html> in the beginning of the document to decide whether to handle it in quirks mode or standards mode.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset=UTF-8>
    <title>Hello World!</title>
  </head>
  <body>
  </body>
</html>

Q. What is difference between HTML and XHTML?

The Extensible Hypertext Markup Language, or XHTML, has two important notes for front end developers.
1) It needs to be well formed, meaning all elements need to be closed and nested correctly or you will return errors.
2) Since it is more strict than HTML is requires less pre-processing by the browser, which may improve your sites performance.

Q. What are the building blocks of HTML5?

  cookie localStorage sessionStorage
Initiator Client or server. Server can use Set-Cookie header Client Client
Expiry Manually set Forever On tab close
Persistent across browser sessions Depends on whether expiration is set Yes No
Sent to server with every HTTP request Cookies are automatically being sent via Cookie header No No
Capacity (per domain) 4kb 5MB 5MB
Accessibility Any window Any window Same tab

Note: If the user decides to clear browsing data via whatever mechanism provided by the browser, this will clear out any cookie, localStorage, or sessionStorage stored. It’s important to keep this in mind when designing for local persistance, especially when comparing to alternatives such as server side storing in a database or similar (which of course will persist despite user actions).

↥ back to top

Q. What is progressive rendering?

TODO

Q. What is Critical Rendering Path?

↥ back to top

Q. What are the Benefits of Server Side Rendering (SSR) Over Client Side Rendering (CSR)?

Q. What is the difference between a <span> and a <div>?

Q. Name 5 common block-level and inline HTML elements.

↥ back to top

Q. What are semantic and non-semantic elements?

Q. What is the purpose of main element?

The HTML <main> element represents the dominant content of the <body> of a document. The main content area consists of content that is directly related to or expands upon the central topic of a document, or the central functionality of an application.

<main role="main">
    <p>Geckos are a group of usually small, usually nocturnal lizards. 
       They are found on every continent except Australia.</p>
    <p>Many species of gecko have adhesive toe pads which enable them to climb walls and even windows.</p>
</main>

Note: A document mustn’t have more than one <main> element that doesn’t have the hidden attribute specified.

↥ back to top

Q. Define semantic markup. What are the semantic meanings for <section>, <article>, <aside>, <nav>, <header>, <footer> and when/how should each be used in structuring html markup?

Q. When should you use section, div or article?

↥ back to top

Q. What is Character Encoding?

Character encoding is a method of converting bytes into characters. To validate or display an HTML document properly, a program must choose a proper character encoding. This is specified in the tag:

<meta charset="utf-8"/>

Q. What is the purpose of meta tags?

The META elements can be used to include name/value pairs describing properties of the HTML document, such as author, expiry date, a list of keywords, document author etc.

<!DOCTYPE html>
<html>
  <head>
        <!--Recommended Meta Tags-->
        <meta charset="utf-8">
        <meta name="language" content="english"> 
        <meta http-equiv="content-type" content="text/html">
        <meta name="author" content="Author Name">
        <meta name="designer" content="Designer Name">
        <meta name="publisher" content="Publisher Name">
        <meta name="no-email-collection" content="name@email.com">
        <meta http-equiv="X-UA-Compatible" content="IE=edge"/>

        <!--Search Engine Optimization Meta Tags-->
        <meta name="description" content="Project Description">
        <meta name="keywords" content="Software Engineer,Product Manager,Project Manager,Data Scientist">
        <meta name="robots" content="index,follow">
        <meta name="revisit-after" content="7 days">
        <meta name="distribution" content="web">
        <meta name="robots" content="noodp">
        
        <!--Optional Meta Tags-->
        <meta name="distribution" content="web">
        <meta name="web_author" content="">
        <meta name="rating" content="">
        <meta name="subject" content="Personal">
        <meta name="title" content=" - Official Website.">
        <meta name="copyright" content="Copyright 2020">
        <meta name="reply-to" content="">
        <meta name="abstract" content="">
        <meta name="city" content="Bangalore">
        <meta name="country" content="INDIA">
        <meta name="distribution" content="">
        <meta name="classification" content="">
    
        <!--Meta Tags for HTML pages on Mobile-->
        <meta name="format-detection" content="telephone=yes"/>
        <meta name="HandheldFriendly" content="true"/> 
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/> 
        <meta name="apple-mobile-web-app-capable" content="yes" />
        
        <!--http-equiv Tags-->
        <meta http-equiv="Content-Style-Type" content="text/css">
        <meta http-equiv="Content-Script-Type" content="text/javascript">
      
    <title>HTML5 Meta Tags</title>
  </head>
  <body>
       ...
  </body>
</html>
↥ back to top

Q. What does async and defer refer in script tag? Describe the difference between <script>, <script async> and <script defer>

The async attribute is used to indicate to the browser that the script file can be executed asynchronously. The HTML parser does not need to pause at the point it reaches the script tag to fetch and execute, the execution can happen whenever the script becomes ready after being fetched in parallel with the document parsing.

The defer attribute tells the browser to only execute the script file once the HTML document has been fully parsed.

Q. If you have 5 different stylesheets, how would you best integrate them into the site?

Break them up onto to different CDN servers to leverage domain sharding.

Employ the “new old” technique of adding “above the fold” css inline in the head of your document – reducing http requests and improve perceived performance.

Using SASS I would break up my files into related chunks – all of which are concatenated and compressed using compass, sass with gulp or grunt in your build process.

↥ back to top

Q. Can you describe the difference between progressive enhancement and graceful degradation?

Q. What is the purpose of cache busting and how can you achieve it?

Browsers have a cache to temporarily store files on websites so they don’t need to be re-downloaded again when switching between pages or reloading the same page. The server is set up to send headers that tell the browser to store the file for a given amount of time. This greatly increases website speed and preserves bandwidth.

However, it can cause problems when the website has been changed by developers because the user’s cache still references old files. This can either leave them with old functionality or break a website if the cached CSS and JavaScript files are referencing elements that no longer exist, have moved or have been renamed.

Cache busting is the process of forcing the browser to download the new files. This is done by naming the file something different to the old file.

A common technique to force the browser to re-download the file is to append a query string to the end of the file.

    src="js/script.js" => src="js/script.js?v=2"

The browser considers it a different file but prevents the need to change the file name.

↥ back to top

Q. Name 3 ways to decrease page load?

  1. LocalStorage
  2. Caching resources
  3. DNS-prefetch (sample below)
  4. Keep resources on a CDN

Q. Explain what ARIA and screenreaders are, and how to make a website accessible.

Screen readers are software programs that provide assistive technologies that allow people with disabilities (such as no sight, sound or mouse-ing ability) to use web applications. You can make your sites more accessible by following ARIA standards such as semantic HTML, alt attributes and using [role=button] in the expected ways

Q. What is the purpose of the alt attribute on images?

The alt attribute provides alternative information for an image if a user cannot view it. The alt attribute should be used to describe any images except those which only serve a decorative purposes, in which case it should be left empty.

Q. Explain some of the pros and cons for CSS animations versus JavaScript animations.

Regarding optimization and responsiveness the debate bounces back and forth but, the concept is:

↥ back to top

Q. What does CORS stand for and what issue does it address?

Cross-Origin Resource Sharing (CORS) is a W3C spec that allows cross-domain communication from the browser. By building on top of the XMLHttpRequest object, CORS allows developers to work with the same idioms as same-domain requests. CORS gives web servers cross-domain access controls, which enable secure cross-domain data transfers.

Q. Ways to improve website performance

↥ back to top

Q. Comparison of browsers engines like Chrome, Firefox, Internet explorer, Safari?

Q. What does the lang attribute in html do?

Q. What is desktop first and mobile first design approach

↥ back to top

Q. What kind of things must you be wary of when design or developing for multilingual sites?

↥ back to top

Q. What are data- attributes good for?

Q. Explain the difference between layout, painting and compositing.

alt text

↥ back to top

Q. Explain about HTML Canvas?

canvas is an HTML element which can be used to draw graphics via JavaScript. This can, for instance, be used to draw graphs, combine photos, or create animations.

Colors, Styles, and Shadows

Property Description
fillStyle Sets or returns the color, gradient, or pattern used to fill the drawing
strokeStyle Sets or returns the color, gradient, or pattern used for strokes
shadowColor Sets or returns the color to use for shadows
shadowBlur Sets or returns the blur level for shadows
shadowOffsetX Sets or returns the horizontal distance of the shadow from the shape
shadowOffsetY Sets or returns the vertical distance of the shadow from the shape

Line Styles

Property Description
lineCap Sets or returns the style of the end caps for a line
lineJoin Sets or returns the type of corner created, when two lines meet
lineWidth Sets or returns the current line width
miterLimit Sets or returns the maximum miter length

Rectangles

Method Description
rect() Creates a rectangle
fillRect() Draws a “filled” rectangle
strokeRect() Draws a rectangle (no fill)
clearRect() Clears the specified pixels within a given rectangle

Paths

Method Description
fill() Fills the current drawing (path)
stroke() Actually draws the path you have defined
beginPath() Begins a path, or resets the current path
moveTo() Moves the path to the specified point in the canvas, without creating a line
closePath() Creates a path from the current point back to the starting point
lineTo() Adds a new point and creates a line to that point from the last specified point in the canvas
clip() Clips a region of any shape and size from the original canvas
arc() Creates an arc/curve (used to create circles, or parts of circles)
arcTo() Creates an arc/curve between two tangents

Transformations

Method Description
scale() Scales the current drawing bigger or smaller
rotate() Rotates the current drawing
translate() Remaps the (0,0) position on the canvas
transform() Replaces the current transformation matrix for the drawing
setTransform() Resets the current transform to the identity matrix. Then runs transform()

Text

|Property |Description | |—————|—————————————————————– | |font |Sets or returns the current font properties for text content | |textAlign |Sets or returns the current alignment for text content | |textBaseline |Sets or returns the current text baseline used when drawing text | |fillText() |Draws “filled” text on the canvas | |strokeText() |Draws text on the canvas (no fill) | |measureText() |Returns an object that contains the width of the specified text |

↥ back to top

Q. Explain about HTML Layout Engines used by browsers?

Engine Status Embedded in
WebKit Active Safari browser, plus all browsers hosted on the iOS App Store
Blink Active Google Chrome and all other Chromium-based browsers like Opera and Microsoft Edge
Gecko Active Firefox browser and Thunderbird email client, plus forks like SeaMonkey and Waterfox
KHTML Discontinued Konqueror browser
Presto Discontinued formerly in the Opera browser
EdgeHTML Discontinued formerly in the Microsoft Edge browser
Trident Discontinued Internet Explorer browser and Microsoft Outlook email client
↥ back to top

Q. What are the semantic tags available in html5?

HTML5 semantic tags define the function and the category of your text, simplifying the work for browsers and search engines, as well as developers.

HTML5 offers new semantic elements to define different parts of a web page:

Syntax:

<header></header>
<section>
	<article>
		<figure>
			<img>
			<figcaption></figcaption>
		</figure>
	</article>
</section>
<footer></footer>

Example: HTML5 Semantic Tags

↥ back to top

Q. Why you would like to use semantic tag. Why Semantic HTML is Important?

Q. How to make page responsive?

Responsive Web Design is about using HTML and CSS to automatically resize, hide, shrink, or enlarge, a website, to make it look good on all devices (desktops, tablets, and phones).

* **Responsive Images**  
If the CSS width property is set to 100%, the image will be responsive and scale up and down
```html
<img src="img.png" style="width:100%;">
Image
* **Responsive Text Size**  
The text size can be set with a "vw" unit, which means the "viewport width". That way the text size will follow the size of the browser window.
```html
<h1 style="font-size:10vw">Hello World</h1>
↥ back to top

Q. What is difference between span tag and div tag?

The primary difference between a div and a span is their default behavior. By default, a <div> is a block-level-element and a <span> is an inline element.

<div>Demo Text, with <span>some other</span> text.</div>

Q. What are optional closing tag?

<p>, <li>, <td>, <tr>, <th>, <html>, <body>, etc. don’t have to provide end tag. Whenever browser hits a new tag it automatically ends the previous tag.

Q. What is a self closing tag?

In HTML5 it is not strictly necessary to close certain HTML tags. The tags that aren’t required to have specific closing tags are called “self closing” tags.

An example of a self closing tag is something like a line break (<br />) or the meta tag (<meta>). This means that the following are both acceptable:

<meta charset="UTF-8">
...
<meta charset="UTF-8" />

Q. Does the following trigger http request at the time of page load?

<img src="mypic.jpg" style="visibility: hidden" alt="My photo">

<div style="display: none;">
    <img src="mypic.jpg" alt="My photo">
</div>

Q. How Geo-location API works in html5?

The Geolocation API allows the user to provide their location to web applications if they so desire. For privacy reasons, the user is asked for permission to report location information.

The Geolocation API is published through the navigator.geolocation object.

if ("geolocation" in navigator) {
  /* geolocation is available */
} else {
  /* geolocation IS NOT available */
}

Example: HTML5 Geolocation API

↥ back to top

Q. What is difference between SVG and Canvas?

SVG: The Scalable Vector Graphics (SVG) is an XML-based image format that is used to define two-dimensional vector based graphics for the web. Unlike raster image (e.g. .jpg, .gif, .png, etc.), a vector image can be scaled up or down to any extent without losing the image quality.

There are following advantages of using SVG over other image formats like JPEG, GIF, PNG, etc.

Example:

<!DOCTYPE html>
<html>
   <head>
      <style>
         #svgelem {
            position: relative;
            left: 50%;
            -webkit-transform: translateX(-20%);
            -ms-transform: translateX(-20%);
            transform: translateX(-20%);
         }
      </style>
      <title>HTML5 SVG</title>
   </head>
   <body>
      <h2 align="center">HTML5 SVG Circle</h2>
      <svg id="svgelem" height="200" xmlns="http://www.w3.org/2000/svg">
         <circle id="bluecircle" cx="60" cy="60" r="50" fill="blue" />
      </svg>
   </body>
</html>

Example: HTML5 SVG

Canvas: Canvas is a HTML element is used to draw graphics on a web page. It is a bitmap with an “immediate mode” graphics application programming interface (API) for drawing on it. The element is only a container for graphics. In order to draw the graphics, you are supposed to use a script. Canvas has several strategies when it comes to drawing paths, boxes, circles, text & adding images.

Example:

<!DOCTYPE html>
<html>
   <head>
      <title>HTML5 Canvas Tag</title>
   </head>
   <body>
      <canvas id="newCanvas" width="200" height="100" style="border:1px solid #000000;"></canvas>
      <script>
         var c = document.getElementById('newCanvas');
         var ctx = c.getContext('2d');
         ctx.fillStyle = '#7cce2b';
         ctx.fillRect(0,0,300,100);
      </script>
   </body>
</html>

Example: HTML5 canvas

Differences between SVG and Canvas

SVG Canvas
Vector based (composed of shapes) Raster based (composed of pixel)
Multiple graphical elements, which become the part of the page’s DOM tree Single element similar to in behavior. Canvas diagram can be saved to PNG or JPG format
Modified through script and CSS Modified through script only
Good text rendering capabilities Poor text rendering capabilities
Give better performance with smaller number of objects or larger surface, or both Give better performance with larger number of objects or smaller surface, or both
Better scalability. Can be printed with high quality at any resolution. Pixelation does not occur Poor scalability. Not suitable for printing on higher resolution. Pixelation may occur
↥ back to top

Q. Explain Drag and Drop in HTML5.

HTML5 drag-and-drop uses the DOM event model and drag events inherited from mouse events. A typical drag operation begins when a user selects a draggable element, drags the element to a droppable element, and then releases the dragged element.

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.

Example

<!DOCTYPE HTML>
<html>
   <head>
   <script>
        function allowDrop(ev) {
            ev.preventDefault();
        }

        function drag(ev) {
            ev.dataTransfer.setData("text", ev.target.id);
        }

        function drop(ev) {
            ev.preventDefault();
            var data = ev.dataTransfer.getData("text");
            ev.target.appendChild(document.getElementById(data));
        }
    </script>
</head>
<body>
  <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
  <img id="drag1" src="img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69">
</body>
</html>

Q. Why to use IndexedDB instead of WebSQL in HTML5?

WebSQL is an API that is only supported in Chrome and Safari (and Android and iOS by extension). It provides an asynchronous, transactional interface to SQLite. Since 2010, it has been deprecated in favor of IndexedDB.

Advantages

Disadvantages

IndexedDB is the successor to both LocalStorage and WebSQL, designed to replace them as the “one true” browser database. It exposes an asynchronous API that supposedly avoids blocking the DOM, but as we’ll see below, it doesn’t necessarily live up to the hype. Browser support is extremely spotty, with only Chrome and Firefox having fully usable implementations.

Advantages

Disadvantages

↥ back to top

Q. Explain Application Cache in HTML5. OR What is a manifest file in HTML?

HTML5 provides an application caching mechanism that lets web-based applications run offline. Developers can use the Application Cache (AppCache) interface to specify resources that the browser should cache and make available to offline users. Applications that are cached load and work correctly even if users click the refresh button when they are offline.

Using an application cache gives an application the following benefits:

Syntax:

<html manifest="example.appcache">
  ...
</html>

Example: HTML5 Application Cache

Note: Using the application caching feature described here is at this point highly discouraged; it’s in the process of being removed from the Web platform. Use Service Workers instead. In fact as of Firefox 44, when AppCache is used to provide offline support for a page a warning message is now displayed in the console advising developers to use Service workers instead (bug 1204581).

Q. Explain Microdata in HTML5.

Microdata is a standardized way to provide additional semantics in web pages. Microdata lets you define your own customized elements and start embedding custom properties in your web pages. At a high level, microdata consists of a group of name-value pairs.

The groups are called items, and each name-value pair is a property. Items and properties are represented by regular elements. Search engines benefit greatly from direct access to this structured data because it allows search engines to understand the information on web pages and provide more relevant results to users.

At a high level, microdata consists of a group of name-value pairs

Example

<div itemscope>
    <p>My name is <span itemprop="name">Elizabeth</span>.</p>
</div>

<div itemscope>
    <p>My name is <span itemprop="name">Daniel</span>.</p>
</div>
↥ back to top

Q. List the API available in HTML5.

High Resolution Time API
The High Resolution Time API provides the current time in sub-millisecond resolution and such that it is not subject to system clock skew or adjustments.

It exposes only one method, that belongs to the window.performance object, called now(). It returns a DOMHighResTimeStamp representing the current time in milliseconds. The timestamp is very accurate, with precision to a thousandth of a millisecond, allowing for accurate tests of the performance of our code.

var time = performance.now();

User Timing API
It allows us to accurately measure and report the performance of a section of JavaScript code. It deals with two main concepts: mark and measure. The former represents an instant (timestamp), while the latter represents the time elapsed between two marks.

performance.mark("startFoo");
// A time consuming function
foo();
performance.mark("endFoo");

performance.measure("durationFoo", "startFoo", "endFoo");

Network Information API
This API belongs to the connection property of the window.navigator object. It exposes two read-only properties: bandwidth and metered. The former is a number representing an estimation of the current bandwidth, while the latter is a Boolean whose value is true if the user’s connection is subject to limitation and bandwidth usage, and false otherwise.

Sl.No API Description
01. navigator.connection.type Network Type
02. navigator.connection.downlink Effective bandwidth estimate ( downlink )
03. navigator.connection.rtt Effective round-trip time estimate ( rtt )
04. navigator.connection.downlinkMax Upper bound on the downlink speed of the first network hop ( downlinkMax )
05. navigator.connection.effectiveType Effective connection type
06. navigator.connection.saveData True if the user has requested a reduced data usage mode from the user agent ( saveData )

Vibration API
It exposes only one method, vibrate(), that belongs to the window.navigator object. This method accepts one parameter specifying the duration of the vibration in milliseconds. The parameter can be either an integer or an array of integers. In the second case, it’s interpreted as alternating vibration times and pauses.

// Vibrate once for 2 seconds
navigator.vibrate(2000);

Battery Status API
The Battery Status API exposes four properties (charging, chargingTime, discharingTime, and level) and four events. The properties specify if the battery is in charge, the seconds remaining until the battery is fully charged, the seconds remaining until the battery is fully discharged, and the current level of the battery. These properties belongs to the battery property of the window.navigator object.

// Retrieves the percentage of the current level of the device's battery
var percentageLevel = navigator.battery.level * 100;

Page Visibility API
The Page Visibility API enables us to determine the current visibility state of the page. The Page Visibility API is especially useful for saving resources and improving performance by letting a page avoid performing unnecessary tasks when the document isn’t visible.

//document.hidden retuns true if page is not visible.
console.log('Page Visibility: '+document.hidden); 

Fullscreen API
The Fullscreen API provides a way to request fullscreen display from the user, and exit this mode when desired. This API exposes two methods, requestFullscreen() and exitFullscreen(), allowing us to request an element to become fullscreen and to exit fullscreen.

document.addEventListener("keypress", function(e) {
    if (e.keyCode === 13) { // Enter Key
        toggleFullScreen();
    }
}, false);

function toggleFullScreen() {
    if (!document.fullscreenElement) {
        document.documentElement.requestFullscreen();
    } else {
        if (document.exitFullscreen) {
        document.exitFullscreen(); 
        }
    }
}

Example: HTML5 API

↥ back to top

Q. What are different new form element types provided by HTML5?

Sl.No Element Description
01. color Gives the end user a native color picker to choose a color.
02. date Offers a datepicker.
03. datetime An element to choose both date and time.
04. datetime-local An element to choose both date and time, with local settings support.
05. email A field for entering e-mail address(es).
06. month Choose a full month.
07. number Picking a number.
08. range Offers a slider to set to a certain value/position.
09. search A field for search queries.
10. tel Choosing a telephone number.
11. time Input a certain time.
12. url Entering a URL.
13. week Picking a specific week.

Example:

<input type="color" value="#b97a57">

<input type="date" value="2020-06-08">

<input type="datetime" value="2020-06-09T20:35:34.32">

<input type="datetime-local" value="2020-06-09T22:41">

<input type="email" value="robert@robertnyman.com">

<input type="month" value="2020-06">

<input type="number" value="4">

<input type="range" value="15">

<!-- Note: If not set, default attribute values are min="0", max="100", step="1". -->

<input type="search" value="[Any search text]">

<input type="tel" value="[Any numeric value]">

<!-- Note: Most web browsers seem to let through any value at this time. -->

<input type="time" value="22:38">

<input type="url" value="https://www.google.com/">

<!-- Note: requires a protocol like http://, ftp:// etc in the beginning. -->


<input type="week" value="2020-W24">
↥ back to top

Q. What are the HTML tags which deprecated in HTML5?

Deprecated Tags
The following elements are not available in HTML5 anymore and their function is better handled by CSS.

Sl.No Tags (Elements) Description
01. <acronym> Defines an acronym
02. <applet> Defines an applet
03. <basefont> Defines an base font for the page.
04. <big> Defines big text
05. <center> Defines centered text
06. <dir> Defines a directory list
07. <font> Defines text font, size, and color
08. <frame> Defines a frame
08. <frameset> Defines a set of frames
10. <isindex> Defines a single-line input field
11. <noframes> Defines a noframe section
12. <s> Defines strikethrough text
13. <strike> Defines strikethrough text
14. <tt> Defines teletype text
15. <u> Defines underlined text

Deprecated Attributes

Removed Attributes From the Elements
rev link, a
charset link and a
shape a
coords a
longdesc img and iframe.
target link
nohref area
profile head
version html
name img
scheme meta
archive object
classid object
codebase object
codetype object
declare object
standby object
valuetype param
type param
axis td and t
abbr td and t
scope td
align caption, iframe, img, input, object, legend, table, hr, div, h1, h2, h3, h4, h5, h6, p, col, colgroup, tbody, td, tfoot, th, thead and tr.
alink body
link body
vlink body
text body
background body
bgcolor table, tr, td, th and body.
border table and object.
cellpadding table
cellspacing table
char col, colgroup, tbody, td, tfoot, th, thead and tr.
charoff col, colgroup, tbody, td, tfoot, th, thead and tr.
clear br
compact dl, menu, ol and ul.
frame table
compact dl, menu, ol and ul.
frame table
frameborder iframe
hspace img and object.
vspace img and object.
marginheight iframe
marginwidth iframe
noshade hr
nowrap td and th
rules table
scrolling iframe
size hr
type li, ol and ul.
valign col, colgroup, tbody, td, tfoot, th, thead and tr
width hr, table, td, th, col, colgroup and pre.
↥ back to top

Q. How you can Use Modernizr in HTML5?

Modernizr is a JavaScript library that detects which HTML5 and CSS3 features visitor’s browser supports. In detecting feature support, it allows developers to test for some of the new technologies and then provide fallbacks for browsers that do not support them. This is called feature detection and is much more efficient than browser sniffing.

Using Modernizr with CSS
By default, Modernizr sets classes for all of your tests on the root element (<html> for websites). This means adding the class for each feature when it is supported, and adding it with a no- prefix when it is not (e.g. .feature or .no-feature).

.no-cssgradients .header {
  background: url("images/glossybutton.png");
}

.cssgradients .header {
  background-image: linear-gradient(cornflowerblue, rebeccapurple);
}

Using Modernizr with JavaScript
Modernizr keeps track of the results of all of it’s feature detections via the Modernizr object.

if (Modernizr.canvas) {
    alert("This browser supports HTML5 canvas!");
} else {
    alert("no canvas :(");
}

Q. What is the use of WebSocket API?

The WebSocket API is an advanced technology that makes it possible to open a two-way interactive communication session between the user’s browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply.

Interfaces

Sl.No API Description
01. WebSocket The primary interface for connecting to a WebSocket server and then sending and receiving data on the connection.
02. CloseEvent The event sent by the WebSocket object when the connection closes.
03. MessageEvent The event sent by the WebSocket object when a message is received from the server.

Example

 // Create WebSocket connection.
const socket = new WebSocket('ws://localhost:8080/');

// Connection opened
socket.addEventListener('open', function(event) {
    socket.send('Hello Server!');
});

// Listen for messages
socket.addEventListener('message', function(event) {
    console.log('Message from server ', event.data);
});
↥ back to top

Q. What does enctype='multipart/form-data' mean?

The enctype attribute specifies how the form-data should be encoded when submitting it to the server.

Example: 01

<form action="fileupload.php" method="post" enctype="multipart/form-data"> 
    <p>Please select the file you would like to upload.</p> 
    <input type="file" name="upload"> 
    <br> 
    <input type="submit" value="Upload File">
</form>

Example: 02

<form action="/urlencoded?token=A87412B" method="POST" enctype="application/x-www-form-urlencoded">
    <input type="text" name="username" value=""/>
    <input type="text" name="password" value=""/>
    <input type="submit" value="Submit" />
</form>

Example: 03

<form action="action.do" method="get" enctype="text/plain">
    Name: <input type="text" name="name" />
    Phone: <input type="number" name="phone" />
    <input type="submit" value="Submit" />
</form>
Sl.No Value Description
01. application/x-www-form-urlencoded Default. All characters are encoded before sent (spaces are converted to “+” symbols, and special characters are converted to ASCII HEX values)
02. multipart/form-data No characters are encoded. This value is required when you are using forms that have a file upload control
03. text/plain Spaces are converted to “+” symbols, but no special characters are encoded
↥ back to top