HTML5 Developer Interview Questions for Freshers
1.
New features of html5
HTML5 is the fifth revision of the Hypertext Markup Language (HTML), which is the standard markup language for creating webpages and applications on the World Wide Web. It was developed by the World Wide Web Consortium (W3C) and the Web Hypertext Application Technology Working Group (WHATWG) as an evolution of its predecessor, HTML4.
2. `<nav>`: Defines a section containing navigation links.
Example:
3. `<main>`: Represents the main content of the document.
Example:
4. `<article>`: Defines a self-contained composition within a document, such as a blog post, news article, or comment.
Example:
5. `<section>`: Represents a standalone section within a document, which could have its own heading.
Example:
6. `<aside>`: Defines a section that contains content related to the main content but can be considered separate from it.
Example:
7. `<footer>`: Represents the footer of a document or a section.
Example:
These are just a few examples of semantic elements in HTML. Using semantic tags helps improve the accessibility, maintainability, and search engine optimization of web pages by providing clearer structural meaning to the content.
2. Multimedia Support: HTML5 added native support for multimedia elements, eliminating the need for plugins like Adobe Flash. The `<audio>` and `<video>` elements allow developers to embed audio and video content directly into web pages. The new `<canvas>` element enables dynamic rendering of graphics, animations, and visual effects using JavaScript.
1. `<audio>`: Embeds an audio file on a web page.
Example:
2. `<video>`: Embeds a video file on a web page.
Example:
3. `<source>`: Specifies alternative media resources for `<audio>` and `<video>` elements.
Example:
4. `<track>`: Specifies timed text tracks, such as captions or subtitles, for `<video>` and `<audio>` elements.
Example:
6. `<embed>`: Embeds external content, such as plugins or multimedia content, within an HTML document.
Example:
These HTML5 multimedia elements allow you to include audio, video, graphics, and external content into your web pages, providing a richer and more interactive user experience.
3. Form Enhancements: HTML5 introduced new input types and attributes to enhance web forms. Some examples include `<input type="email">` for email addresses, `<input type="url">` for URLs, `<input type="date">` for date input, `<input type="range">` for sliders, and `<input type="color">` for color pickers. Additionally, the `<datalist>` element provides a list of predefined options for form fields.
1. Input types:
HTML5 introduced new input types that provide better input validation and user experience. For example:
2. Placeholder attribute:
The placeholder attribute allows you to provide hints or example values within input fields. It disappears when the user starts typing.
3. Required attribute:
The required attribute specifies that an input field must be filled out before submitting the form.
4. Pattern attribute:
The pattern attribute allows you to specify a regular expression pattern that the input value must match.
5. Date input:
HTML5 introduced the `<input type="date">` element, which provides a date picker for selecting dates.
6. Color input:
The `<input type="color">` element allows users to select a color using a color picker.
7. Range input:
The `<input type="range">` element creates a slider control for selecting a value within a specified range.
8. Autocomplete attribute:
The autocomplete attribute specifies whether a form field should have autocomplete functionality enabled or disabled.
9. Validation:
HTML5 introduced built-in form validation, which allows you to validate form inputs without using JavaScript. You can use attributes like `required`, `min`, `max`, `pattern`, and more to validate user input.
These are just a few examples of the form enhancements introduced in HTML5. These features help improve user experience, provide better input validation, and reduce the need for custom JavaScript solutions when working with forms.
4. Offline and Storage: HTML5 introduced the Application Cache (`<appcache>`) mechanism, enabling web applications to work offline or with a slow internet connection. It also introduced the Web Storage API (`localStorage` and `sessionStorage`), allowing web applications to store data locally on the client's browser.
1. Application Cache (Offline):
HTML5 introduced the Application Cache feature, which allows web pages to be cached on the client-side and accessed offline. By defining a cache manifest file, you can specify which resources should be stored for offline use.
Example:
The `offline.appcache` file would contain a list of resources to cache.
2. Local Storage:
HTML5 provides the Local Storage API, allowing you to store key-value pairs of data on the client's browser. This data persists even after the browser is closed.
Example:
3. Session Storage:
Similar to Local Storage, the Session Storage API allows you to store data on the client-side. However, the data is available only for the duration of the browser session and is cleared when the session ends.
Example:
4. IndexedDB:
IndexedDB is a more advanced client-side database feature introduced in HTML5. It provides a structured, indexed storage solution for larger sets of data.
Example:
These offline and storage features in HTML5 provide web developers with the ability to create more robust and capable web applications that can function offline and store data locally on the client-side.
5. Geolocation: HTML5 introduced the Geolocation API, which enables web applications to access the user's geographic location with their consent. This feature has been widely used for location-based services and applications.
Here's an example of using the Geolocation API in HTML5:
In this example:
1. The `getLocation()` function is called when the user clicks the "Get Location" button.
2. The function checks if the browser supports the Geolocation API. If supported, it calls the `getCurrentPosition()` method, passing in the `showPosition` function as the success callback and the `showError` function as the error callback.
3. If the user grants permission to access their location, the `showPosition()` function is called with the `position` parameter containing the latitude and longitude coordinates.
4. If an error occurs, the `showError()` function is called, providing information about the specific error that occurred.
When the user clicks the "Get Location" button, the web page will prompt the user to grant permission to access their location. If permission is granted, the browser will retrieve the latitude and longitude coordinates, and an alert dialog will display the coordinates. If an error occurs or if geolocation is not supported, an appropriate alert message will be displayed.
Please note that accessing geolocation requires the user's consent, and the accuracy of the retrieved location can vary depending on various factors, such as the user's device and browser settings.
6. Drag and Drop: HTML5 introduced a standardized Drag and Drop API, making it easier to implement drag-and-drop functionality within web applications without relying on third-party libraries.
In this example:
1. Two draggable elements with IDs "dragitem1" and "dragitem2" are created. The `draggable="true"` attribute allows them to be dragged.
2. The `drag()` function is called when the drag operation starts, and it sets the ID of the dragged element as the data to be transferred during the drag.
3. The `allowDrop()` function is called when an element is dragged over the drop zone. It prevents the default behavior to allow dropping.
4. The `drop()` function is called when an element is dropped onto the drop zone. It prevents the default behavior, retrieves the data of the dragged element, and appends the dragged element to the drop zone.
When you run this code, you can drag the "Draggable Item 1" and "Draggable Item 2" elements and drop them into the "Drop Zone" element. The `drop()` function is responsible for handling the drop event and moving the dragged element to the drop zone.
This example demonstrates a basic implementation of drag and drop functionality using HTML5. You can customize it further by adding additional event handlers or applying CSS styles to enhance the visual feedback during drag and drop interactions.
7. Improved Accessibility: HTML5 introduced various attributes and elements to improve web accessibility. These include the `role` attribute, `aria-*` attributes for defining accessible roles and properties, and `<figure>` and `<figcaption>` elements for providing alternative descriptions for images and multimedia content.
Here's an example that demonstrates additional HTML5 accessibility features and best practices for improved accessibility:
In this improved example:
1. Heading elements (`<h1>`, `<h2>`, `<h3>`, `<h4>`) are used to provide hierarchical structure and clear headings for different sections.
2. Semantic elements like `<article>`, `<section>`, and `<nav>` are used to indicate the structure and purpose of different parts of the page.
3. Alternative text (`alt` attribute) is provided for images within `<img>` elements, describing the content or purpose of the image.
4. The `<figure>` element is used to group an image and its caption (`<figcaption>`), providing a semantic association between them.
5. An `<aside>` element is used to provide additional related information that is separate from the main content.
6. The `lang` attribute is set to `"en"` to specify the language of the web page.
7. The `<header>` element marks the header section of the page, and the `<footer>` element marks the footer section.
By incorporating these HTML5 accessibility features and best practices, you make the web page more structured, navigable, and understandable for users with disabilities and assistive technologies. Additionally, remember to ensure proper color contrast, provide descriptive link text, and consider keyboard accessibility to further improve the overall accessibility of your web page.
Following are the new features in HTML5 :
1. Semantics: HTML5 introduced several new elements that provide better semantic meaning to web content. These include `<header>`, `<footer>`, `<nav>`, `<article>`, `<section>`, `<aside>`, `<figure>`, and `<figcaption>`. These elements make it easier for search engines and assistive technologies to understand the structure and purpose of the content. Semantic elements in HTML are tags that provide meaning and context to the content within a web page. They help describe the purpose or role of different sections of the document, making it more accessible to both humans and machines. Here are some commonly used semantic elements in HTML: 1. `<header>`: Represents the introductory content or a container for the site's heading, logo, navigation, etc. Example:
<header>
<h1>My Website</h1>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
</header>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
<main>
<h1>Article Title</h1>
<p>Article content goes here.</p>
</main>
<article>
<h2>Blog Post Title</h2>
<p>Blog post content goes here.</p>
<footer>Published on June 1, 2023</footer>
</article>
<section>
<h2>About Us</h2>
<p>Information about our company.</p>
</section>
<aside>
<h3>Related Links</h3>
<ul>
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
</ul>
</aside>
<footer>
<p>© 2023 My Website. All rights reserved.</p>
</footer>
<audio src="audiofile.mp3" controls="">
Your browser does not support the audio element.
</audio>
<video src="videofile.mp4" controls="">
Your browser does not support the video element.
</video>
<video controls="">
<source src="" type="video/mp4">
<source src="" type="video/webm">
Your browser does not support the video element.
</video>
<video controls="">
<source src="" type="video/mp4">
<track src="" kind="captions" label="English" srclang="en">
Your browser does not support the video element.
</video>
<embed src="" width="400" height="300">
<input type="email" placeholder="Email" required>
<input type="date" placeholder="Date">
<input type="number" placeholder="Number">
<input type="range" min="0" max="100" step="5">
<input type="text" placeholder="Enter your name">
<input type="text" required>
<input type="text" pattern="[A-Za-z]{3}">
<input type="date">
<input type="color">
<input type="range" min="0" max="100">
<input type="text" autocomplete="off">
<!DOCTYPE html>
<html manifest="offline.appcache">
...
</html>
<script>
// Store data in local storage
localStorage.setItem('username', 'John');
// Retrieve data from local storage
var username = localStorage.getItem('username');
console.log(username); // Output: John
// Remove data from local storage
localStorage.removeItem('username');
</script>
<script>
// Store data in session storage
sessionStorage.setItem('token', 'abc123');
// Retrieve data from session storage
var token = sessionStorage.getItem('token');
console.log(token); // Output: abc123
// Remove data from session storage
sessionStorage.removeItem('token');
</script>
<script>
// Open a database connection
var request = indexedDB.open('myDatabase', 1);
request.onerror = function(event) {
console.log('Database error: ' + event.target.errorCode);
};
request.onsuccess = function(event) {
var db = event.target.result;
// Perform database operations here
};
</script>
<!DOCTYPE html>
<html>
<head>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
alert("Latitude: " + latitude + "\nLongitude: " + longitude);
}
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
alert("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
alert("Location information is unavailable.");
break;
case error.TIMEOUT:
alert("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
alert("An unknown error occurred.");
break;
}
}
</script>
</head>
<body>
<button onclick="getLocation()">Get Location</button>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<style>
.dropzone {
width: 200px;
height: 200px;
border: 2px dashed #ccc;
padding: 10px;
}
.dragitem {
width: 100px;
height: 100px;
background-color: #f1f1f1;
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
cursor: move;
}
</style>
<script>
function allowDrop(event) {
event.preventDefault();
}
function drag(event) {
event.dataTransfer.setData("text", event.target.id);
}
function drop(event) {
event.preventDefault();
var data = event.dataTransfer.getData("text");
event.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>
<div id="dragitem1" class="dragitem" draggable="true" ondragstart="drag(event)">Draggable Item 1</div>
<div id="dragitem2" class="dragitem" draggable="true" ondragstart="drag(event)">Draggable Item 2</div>
<div id="dropzone" class="dropzone" ondragover="allowDrop(event)" ondrop="drop(event)">
Drop Zone
</div>
</body>
</html>
<!DOCTYPE html><br>
<html lang="en"><br>
<head><br>
<title>Improved Accessible Web Page</title><br>
</head><br>
<body><br>
<header><br>
<h1>Welcome to My Improved Accessible Web Page</h1><br>
</header><br>
<br>
<nav><br>
<ul><br>
<li><a href="#section1">Section 1</a></li><br>
<li><a href="#section2">Section 2</a></li><br>
<li><a href="#section3">Section 3</a></li><br>
</ul><br>
</nav><br>
<br>
<main><br>
<section id="section1"><br>
<h2>Section 1</h2><br>
<article><br>
<h3>Subsection 1.1</h3><br>
<p>This is the content of subsection 1.1.</p><br>
</article><br>
<br>
<article><br>
<h3>Subsection 1.2</h3><br>
<figure><br>
<img src="image.jpg" alt="Description of the image"><br>
<figcaption>A beautiful image</figcaption><br>
</figure><br>
<p>This is the content of subsection 1.2.</p><br>
</article><br>
</section><br>
<br>
<section id="section2"><br>
<h2>Section 2</h2><br>
<article><br>
<h3>Subsection 2.1</h3><br>
<p>This is the content of subsection 2.1.</p><br>
</article><br>
<br>
<article><br>
<h3>Subsection 2.2</h3><br>
<p>This is the content of subsection 2.2.</p><br>
<aside><br>
<h4>Related Information</h4><br>
<p>Additional information about this section.</p><br>
</aside><br>
</article><br>
</section><br>
<br>
<section id="section3"><br>
<h2>Section 3</h2><br>
<article><br>
<h3>Subsection 3.1</h3><br>
<p>This is the content of subsection 3.1.</p><br>
</article><br>
<br>
<article><br>
<h3>Subsection 3.2</h3><br>
<p>This is the content of subsection 3.2.</p><br>
</article><br>
</section><br>
</main><br>
<br>
<footer><br>
<p>© 2023 My Improved Accessible Web Page</p><br>
</footer><br>
</body><br>
</html><br>
2.
Difference between SVG and Canvas
SVG (Scalable Vector Graphics) and Canvas are both graphics technologies in HTML5, but they have different approaches and use cases. Here's the difference between SVG and Canvas:
In summary, SVG is suitable for scalable graphics, interactive visualizations, and accessibility, while Canvas excels in high-performance rendering, pixel-level control, and applications requiring real-time graphics, such as games and animations. The choice between SVG and Canvas depends on the specific requirements and characteristics of the project.
SVG | Canvas | |
---|---|---|
Graphics Type | Vector-based | Bitmap-based |
Scalability | Scalable without losing quality | Not scalable without loss of quality |
Rendering Approach | Retained Mode | Immediate Mode |
Interactivity | Easily modified and interactive | Less interactive once drawn |
Accessibility | Built-in accessibility features | No built-in accessibility features |
Performance | Less performant for complex scenes | High-performance for real-time rendering |
Use Cases | Icons, logos, charts, interactive visuals | Games, animations, image editing |
Language | XML-based markup language | JavaScript-based API |
3.
Difference between localstorage , session storage and cookies
LocalStorage, sessionStorage, and cookies are all mechanisms for storing data on the client-side in a web browser, but they differ in their scope, expiration, and usage. Here's a breakdown of their differences:
LocalStorage:
- Scope: Local to the specific domain/origin.
- Expiration: Data stored in LocalStorage persists even after the browser is closed and is available for future sessions unless explicitly removed.
- Size Limit: Typically, the storage limit is around 5MB.
- Usage: LocalStorage is commonly used for long-term storage of data that needs to be available across multiple browser sessions, such as user preferences or cached data. It provides a simple key-value storage mechanism and is accessible by any page on the same domain.
SessionStorage:
- Scope: Local to the specific domain/origin.
- Expiration: Data stored in sessionStorage is available only within the current browser session. It is cleared when the session ends or when the browser is closed.
- Size Limit: Similar to LocalStorage, sessionStorage typically has a storage limit of around 5MB.
- Usage: sessionStorage is often used for storing temporary or session-specific data. For example, it can be used to store state information during a user's visit to a website, such as a shopping cart contents or form data that needs to be retained temporarily.
Cookies:
- Scope: Cookies are associated with a specific domain and can be set to be accessible across subdomains or restricted to specific paths.
- Expiration: Cookies can have an expiration date/time, allowing them to persist across browser sessions (persistent cookies) or be deleted when the browser is closed (session cookies).
- Size Limit: The maximum size for cookies is typically around 4KB.
- Usage: Cookies are commonly used for storing small amounts of data, such as user preferences, session identifiers, or authentication tokens. They are sent with each request to the server, providing a way to maintain state or track user behavior.
In summary, LocalStorage and sessionStorage are storage mechanisms provided by the browser for client-side data storage, with LocalStorage being more persistent and available across sessions, while sessionStorage is limited to the current session. Cookies, on the other hand, are small text files used for storing data that is sent to the server with each request, and they can have expiration dates for persistence. The choice of which storage mechanism to use depends on the specific requirements of the application and the desired lifespan of the data.
4.
What things should be stored in local storage and what in session storage
LocalStorage and sessionStorage are both web storage options provided by web browsers to store data on the client-side. Here's a general guideline for what types of data are commonly stored in each:
LocalStorage:
LocalStorage is designed for persistent storage of data that needs to be available even after the browser is closed and reopened. It provides a larger storage capacity compared to sessionStorage. Typically, you would store the following types of data in LocalStorage:
1. User Preferences: Storing user-specific settings, preferences, or configurations that persist across multiple sessions.
2. User Authentication Tokens: Storing authentication tokens or session information to keep the user logged in.
3. Cached Data: Caching data that can be reused across different sessions, such as static content, configuration data, or data fetched from APIs.
4. Application State: Storing the state of the application, including user inputs or selections, to restore the application to its previous state when reopened.
SessionStorage:
SessionStorage is designed for storing data that is only needed during a particular browsing session. The data stored in sessionStorage is accessible within the same browser tab or window but is cleared once the tab or window is closed. Typically, you would store the following types of data in sessionStorage:
1. Temporary Data: Storing temporary data or information that is only needed for a specific task or session.
2. Shopping Cart Data: Storing items added to a shopping cart during the user's browsing session.
3. Form Data: Storing form data temporarily, allowing users to navigate between form pages without losing their inputs.
4. Page State: Storing the state of a specific page or component within the session to maintain its functionality during navigation.
It's important to consider the sensitivity and security of the data being stored. Avoid storing sensitive data like passwords, personally identifiable information (PII), or confidential data in either LocalStorage or sessionStorage. Instead, sensitive data should be stored securely on the server-side.
Remember that both LocalStorage and sessionStorage are limited to the client-side and are accessible by JavaScript, so it's important to be cautious about the data you store and ensure that it aligns with your application's security requirements and privacy policies.
5.
what is BOM (browser object model ) and what is the root object in it
The Browser Object Model (BOM) is used to interact with the browser.
The default object of browser is window means you can call all the functions of window by specifying window or directly.
Browser Objects:
The objects listed below are called browser objects.
Window - part of DOM API
Navigator
Document - part of DOM API
Screen - property of Window object
History - property of Window object
Location - property of Window and Document object
6.
What would happen if I would not declare doctype in html
The <!DOCTYPE> declaration must be the very first thing in your HTML document, before the tag.
The <!DOCTYPE> declaration is not an HTML tag; it is an instruction to the web browser about what version of HTML the page is written in.
A lot of IDEs allow users to leave this out and default to a certain HTML style, but leaving it out does pose a potential threat in browser compatibility and the use of older versions of HTML.
For example: new features & tags in HTML5 such as <article>,<footer>, <header>,<nav>, <section> may not be supported if the <!DOCTYPE> is not declared.
7.
What are the void elements in HTML?
Most of the HTML elements are surrounded by start and end tags to specify the starting and end of the element.
There is a special group of elements that only have start tags and does not contain any content within it, these elements are called void elements. Void elements doesn’t have ending tags and can only have attributes but do not contain any kind of content. These elements can have backslash before ending of start tag but that is completely optional. Example of such elements are <br>, <hr>, <img>, <input>, <link>, <base>, <meta>, <param>, <area>, <embed>, <col>,
8.
What are the various formatting tags in HTML?
HTML has various formatting tags:
<b> - makes text bold
<i> - makes text italic
<em> - makes text italic but with added semantics importance
<big> - increases the font size of the text by one unit
<small> - decreases the font size of the text by one unit
<sub> - makes the text a subscript
<sup> - makes the text a superscript
<del> - displays as strike out text
<strong> - marks the text as important
<mark> - highlights the text
<ins> - displays as added text
9.
In how many ways you can display HTML elements?
1. inline: Using this we can display any block-level element as an inline element. The height and width attribute values of
the element will not affect.
2. block: using this, we can display any inline element as a block-level element.
3. inline-block: This property is similar to inline, except by using the display as inline-block, we can actually format the
element using height and width values.
4. flex: It displays the container and element as a flexible structure. It follows flexbox property.
5. inline-flex: It displays the flex container as an inline element while its content follows the flexbox properties.
6. grid: It displays the HTML elements as a grid container.
7. none: Using this property we can hide the HTML element.
10.
What is the purpose of the doctype declaration in HTML5?
The purpose of the doctype declaration in HTML5 is to specify the version of HTML being used in the document and to ensure that the browser renders the webpage in standards mode. The doctype declaration is placed at the very beginning of an HTML document, before the `` tag.
In HTML5, the doctype declaration is simplified and standardized. The following is the basic syntax of the doctype declaration in HTML5:
The above declaration informs the browser that the document is written in HTML5. It triggers the browser to render the webpage in standards mode, where it follows the specifications and rules of HTML5.
In this example, the `<!DOCTYPE html>` declaration is placed at the very beginning. It signifies that the document is an HTML5 document. The rest of the HTML markup follows after the doctype declaration.
Conclusion :
It's important to include the <doctype declaration> to ensure proper rendering and interpretation of the HTML code by web browsers. Without it, the browser might fallback to quirks mode or older rendering modes, leading to inconsistent behavior and potential compatibility issues.
<!DOCTYPE html>
<!DOCTYPE html>
<html>
<head>
<title>My Webpage</title>
</head>
<body>
<h1>Welcome to My Webpage</h1>
<p>This is a sample paragraph.</p>
</body>
</html>