HTML Flashcards
What are HTML5 structure elements
<header> - Used to define header for a document or a section <nav> - Used to define container for navigation links <section> - Used to define a section inside a document <article> - Used to tag an independent self-contained article <aside> - Defines the content separately (just like a sidebar) <footer> - Used for tagging a footer inside a document or a section <details> - Used to define any additional details <summary> - Used to define a heading inside the <details> element <main>
What is the importance of Semantic Markup
- gives structure
- good for SEO
- good for accessibility, screen readers
- easy to maintain
What are web components
Web components are a set of web platform APIs that allow you to create new custom, reusable, encapsulated HTML tags to use in web pages and web apps. You can also create custom versions of standard HTML elements. Some of the elements are
<shadow>, <content>, <element>, <template>, <slot>
What are the 7 layers in OSI model
There are 7 layers in the OSI model:
Physical Layer,
Data Link layer,
Network Layer,
Transport Layer,
Session Layer,
Presentation Layer, and
Application Layer.
async vs defer on script tag
async Attribute
* Functionality: When you add the async attribute to a <script> tag, the script is loaded asynchronously with the rest of the page. This means that the script is downloaded in the background and will execute as soon as it is downloaded, without waiting for the rest of the page to load. * Use Case: async is useful for scripts that do not depend on other scripts and do not modify the DOM (Document Object Model). It ensures that the script does not block page rendering while it is loading.
defer Attribute
* Functionality: The defer attribute, when used, also allows the script to load asynchronously, but it defers the execution of the script until the entire HTML document has been parsed. This means the script execution waits until the HTML parsing is complete but does not block the HTML parsing itself. * Use Case: defer is ideal for scripts that need to access or modify the DOM or when your scripts rely on other scripts that are also deferred. It ensures that the script will only run after the HTML document is fully parsed.
What is accessibility
As the browser parses the content received, it builds the document object model (DOM) and the CSS object model (CSSOM). It then also builds an accessibility tree. Assistive devices, such as screen readers, use the AOM to parse and interpret content. The DOM is a tree of all the nodes in the document. The AOM is like a semantic version of the DOM.
AOM nodes have name, description, role, state
landmark roles - major content areas like banner(header), main, navigation
structure roles - structural information tooltip, list, table
widget roles - interactive elements (tab, button, searchbox)
window roles - dialog, alertdialog
live region role - timer, log, alert (useful for content that is changing like chatbox)
aria-role
aria-live - off, polite, assertive
aria-label - label not visible on UI
aria-labelledby - id of the element that describes it
aria-description
aria-describedby
aria-controls
aria-selected
Browser compatibility
css accessibility - use contrast, legible fonts, mobile support
internationalization i18n
Ensuring the accessibility of a web application is essential for creating inclusive and user-friendly experiences for all users, including those with disabilities. Here are key aspects and best practices to consider:
Key Aspects of Web Accessibility
1. Perceivable: Information and user interface components must be presented in ways that users can perceive. This includes providing text alternatives for non-text content, such as images (<alt> attributes), ensuring content is adaptable to different screen sizes, and using sufficient color contrast. 2. Operable: User interface components and navigation must be operable. This includes making all functionality available from a keyboard, giving users enough time to read and use content, and not designing content in a way that is known to cause seizures. 3. Understandable: Information and the operation of the user interface must be understandable. This involves making text readable and understandable, ensuring web pages operate in predictable ways, and helping users avoid and correct mistakes. 4. Robust: Content must be robust enough to be interpreted reliably by a wide variety of user agents, including assistive technologies. This includes ensuring compatibility with current and future user tools.
Best Practices for Web Accessibility
1. Use Semantic HTML: Use HTML elements according to their purpose (e.g., <header>, <footer>, <article>, <nav>). This helps screen readers and other assistive technologies understand the structure and navigate the content efficiently. 2. Keyboard Navigation: Ensure that all interactive elements (buttons, links, forms) are reachable and operable via keyboard. Use the tabindex attribute wisely to manage focus order. 3. Aria Landmarks and Roles: Use ARIA (Accessible Rich Internet Applications) landmarks and roles to define regions of the page (e.g., <main>, <aside>, <nav>). This helps users with screen readers navigate the content. 4. Provide Text Alternatives: Include text alternatives for all non-text content. This means using alt attributes for images, captions for videos, and transcripts for audio content. 5. Color Contrast: Ensure that text has sufficient contrast against its background. The Web Content Accessibility Guidelines (WCAG) recommend a contrast ratio of at least 4.5:1 for normal text and 3:1 for large text. 6. Responsive Design: Ensure that your website is responsive and works well on various devices and screen sizes. This improves accessibility for users who rely on different devices. 7. Forms Accessibility: Make sure forms are accessible by associating labels with inputs using the for attribute and providing clear instructions and error messages. 8. Skip Navigation: Provide a way for users to skip repetitive content. A common method is a “Skip to main content” link at the top of the page.
Tools and Resources
1. Accessibility Checker Tools: * WAVE: Web Accessibility Evaluation Tool. * Axe: Accessibility testing tool for websites and applications. * Lighthouse: Built into Chrome DevTools for checking various aspects of web performance and accessibility. 2. Guidelines and Standards: * WCAG (Web Content Accessibility Guidelines): The main international standard for web accessibility. Following WCAG helps make content accessible to a wider range of people with disabilities, including blindness and low vision, deafness and hearing loss, learning disabilities, cognitive limitations, limited movement, speech disabilities, and combinations of these. * ARIA (Accessible Rich Internet Applications): Provides a way to make web content and web applications more accessible to people with disabilities. Web accessibility levels are defined by the Web Content Accessibility Guidelines (WCAG), which are a set of recommendations for making web content more accessible. The guidelines are organized into three levels of conformance: A, AA, and AAA. Each level builds upon the previous one, with Level A being the most basic and Level AAA being the most comprehensive.
WCAG Levels Explained
1. Level A (Minimum Accessibility): * Focus: Basic web accessibility that ensures no content is completely inaccessible. * Requirements: Addresses the most critical accessibility barriers that prevent users from using the content altogether. * Examples: * Text alternatives for non-text content (e.g., alt attributes for images). * Keyboard accessibility for all content. * Avoidance of content that can cause seizures (e.g., avoiding flashing content). 2. Level AA (Mid-Range Accessibility): * Focus: Deals with the biggest and most common barriers for disabled users. * Requirements: Aims to make web content accessible to a broader range of people with disabilities. * Examples: * Sufficient color contrast between text and its background. * Text resizing without loss of content or functionality. * Navigation and focus order consistency. * Provision of multiple ways to locate a web page within a set of web pages. 3. Level AAA (High-Level Accessibility): * Focus: The highest and most complex level of web accessibility. * Requirements: Ensures the highest level of accessibility, addressing the needs of the widest range of disabilities. * Examples: * Extended requirements for contrast and text spacing. * Comprehensive support for sign language interpretation for all pre-recorded audio content. * Enhanced navigability and readability of content. * Provision of detailed help and instructions.
Practical Applications
* Level A: Ensures no barriers prevent users from accessing content. Implementing Level A guidelines is a basic requirement for making web content accessible. * Level AA: Addresses the most common barriers and is typically the level of conformance aimed for by most organizations, as it ensures a high level of accessibility for a majority of users. * Level AAA: Suitable for organizations that want to go above and beyond the basic and common barriers, providing the highest accessibility level. Achieving AAA is challenging and not always feasible for all types of content.
HTML Table
<table> <caption>MLW Alumni</caption> <thead> <tr> <th>Name</th> <th>Destiny</th> <th>Year</th> </tr> </thead> <tbody> <tr> <th>Hal Gibrah</th> <td>Calculator</td> <td>2020</td> </tr> <tr> <th>Cathy Terr</th> <td>Waste disposal</td> <td>2018</td> </tr> <tr> <th>Lou Minious</th> <td>Lightbulb</td> <td>1956</td> </tr> </tbody> </table>
attributes
rowspan for tr, colspan for td or th
for styling
~~~
<colgroup>
<col></col>
</colgroup>
~~~
Custom attributes
use data-<name> to create custom attributes.</name>
Get the value using el.getAttribute('data-name');
or el.dataset[name]
tabindex values
Using tabindex
1. Positive Values: Setting tabindex to a positive number (e.g., tabindex="1") places the element in the sequential keyboard navigation order, with the order defined by the value of tabindex. Lower numbers are focused first. This can be useful for creating a specific flow of navigation different from the source order in the HTML, but it should be used sparingly as it can make navigation confusing if overused or used inconsistently. 2. tabindex="0": Adding tabindex="0" to an element makes it reachable via sequential keyboard navigation, using its position in the document structure to determine its order. This is useful for elements that are not focusable by default (like divs and spans) but need to be interactive. 3. Negative Values (tabindex="-1"): Elements with tabindex="-1" are not reachable via the keyboard, but they can be focused programmatically (using JavaScript). This is useful for elements that you might want to focus dynamically without affecting the natural tabbing order of the page.
Meta tags
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>My First Webpage</title> <meta name="viewport" content="width=device-width, initial-scale=1"/> <meta name="author" content="FrontendExpert" /> <meta name="description" content="value"/> <base href="https://algoexpert.io" /> </head> <body> <p> This link is relative to the base: <a href="/frontend" target="_blank">Frontend Expert</a>! </p> </body> </html>
Script type=”module” features
Key Features of type=”module”
1. Scoped Variables: Variables declared in a module are scoped to that module and not global. * This helps in avoiding conflicts with other scripts. 2. Imports and Exports: * Modules can import and export functionality between different JavaScript files. Deferred Execution: * Scripts with type="module" are deferred automatically, which means they will not block the HTML parsing. * They execute in the order they are encountered. 4. Strict Mode: * JavaScript modules always run in strict mode, regardless of whether "use strict" is declared. * This means certain actions that are considered bad practices, like using undeclared variables, will throw errors. 5. Top-Level this is undefined: * In a module, the top-level this is undefined, which is different from scripts where this refers to the global object. 6. Dynamic Imports: * Modules support dynamic import syntax, which allows for loading modules on-demand.
// module.js export function greet() { console.log('Hello, world!'); } // main.js import { greet } from './module.js'; greet(); // Outputs: Hello, world!
Form
<form id="registrationForm" action="/submit" method="post"> <label for="username">Username:</label> <input type="text" id="username" name="username" required minlength="3" maxlength="15"> <br><br> <label for="email">Email:</label> <input type="email" id="email" name="email" required> <br><br> <label for="password">Password:</label> <input type="password" id="password" name="password" required minlength="6"> <br><br> <label for="age">Age:</label> <input type="number" id="age" name="age" required min="18" max="99"> <br><br> <input type="submit" value="Register"> </form> <script> document.getElementById('registrationForm').addEventListener('submit', function(event) { if (!this.checkValidity()) { event.preventDefault(); alert('Please fill out the form correctly.'); } }); </script>
HTML5 offers built-in validation attributes that are easy to use and require minimal effort:
1. required: Ensures the field is not empty. 2. type: Defines the type of data expected, such as email, url, number, date, etc. 3. min and max: Sets minimum and maximum values for numeric and date inputs. 4. pattern: Specifies a regular expression that the input must match. 5. maxlength and minlength: Specifies the maximum and minimum number of characters allowed.
http caching
- use Cache-Control headers in response from server to cache the api response at browser
- use Etags
file/folder viewer js
https://jsfiddle.net/harshdand/ztyd1oa7/108/
Internationalization
Internationalization (i18n) and localization (l10n) are processes to ensure that web applications can support multiple languages and regions. Here is a basic approach to implement internationalization and localization in an HTML and JavaScript-based web application
<h1 data-i18n="greeting"></h1> <p data-i18n="farewell"></p> <button onclick="setLanguage('en')">English</button> <button onclick="setLanguage('es')">Español</button>
const translations = { en: { 'greeting': 'greeting' }, es: { 'greeting': 'dasdfasd' } }; function setLanguage(lang) { if (translations[lang]) { applyTranslation(lang); } } function applyTranslation(lang) { document.querySelectorAll('[data-i18n]').forEach(element => { const key = element.getAttribute('data-i18n'); element.textContent = translations[lang][key]; }); } document.addEventListener('DOMContentLoaded', () => { console.log(navigator.language); const userLang = navigator.language.startsWith('es') ? 'es' : 'en'; // Example language detection setLanguage(userLang); });
or use i18next
<h1 id="greeting"></h1> <p id="farewell"></p> <select id="language-switcher"> <option value="en">English</option> <option value="es">Español</option> </select> document.addEventListener('DOMContentLoaded', () => { i18next.init({ lng: 'en', // default language resources: { en: { translation: { "greeting": "Hello", "farewell": "Goodbye" } }, es: { translation: { "greeting": "Hola", "farewell": "Adiós" } } } }, (err, t) => { if (err) return console.error(err); updateContent(); }); function updateContent() { document.getElementById('greeting').innerHTML = i18next.t('greeting'); document.getElementById('farewell').innerHTML = i18next.t('farewell'); } document.getElementById('language-switcher').addEventListener('change', (event) => { i18next.changeLanguage(event.target.value, updateContent); }); });