40 Advanced HTML Tutorials

40 Advanced HTML Tutorials

1. Custom Data Attributes Advanced

Advanced use of custom data attributes involves storing complex JSON data and accessing them via JavaScript for dynamic behavior.

Example: Storing JSON in data attribute.

<div data-config='{ "color": "blue", "size": 10 }'>Element with config</div>
<script>
const elem = document.querySelector('div');
const config = JSON.parse(elem.dataset.config);
elem.style.color = config.color;
elem.style.fontSize = `${config.size}px`;
</script>
Element with config

Note: Ensure JSON is valid to avoid parsing errors. This technique is useful for passing server-generated data to client-side scripts.

2. Advanced ARIA Patterns

Advanced ARIA patterns involve using attributes like aria-live for dynamic content updates and aria-describedby for additional descriptions.

Example: Live region for updates.

<div aria-live="polite" id="live-region">Initial message</div>
<button onclick="document.getElementById('live-region').innerText = 'Updated message'">Update</button>
Initial message

Note: Use aria-live="polite" for non-urgent updates to avoid interrupting screen readers. Test with screen readers like NVDA or VoiceOver.

3. HTML5 Web Components Basics

Web Components allow creation of reusable custom elements using custom elements, shadow DOM, and templates.

Example: Basic custom element.

<script>
class MyElement extends HTMLElement {
connectedCallback() {
this.innerHTML = '<p>Custom Element Content</p>';
}
}
customElements.define('my-element', MyElement);
</script>
<my-element></my-element>

Note: Web Components promote encapsulation and reusability. Ensure polyfills for older browsers if needed.

4. Shadow DOM in HTML

Shadow DOM encapsulates styles and markup in a custom element, preventing global CSS interference.

Example: Shadow DOM element.

<script>
class ShadowElement extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({mode: 'open'});
shadow.innerHTML = '<style>p { color: red; }</style><p>Shadow Content</p>';
}
}
customElements.define('shadow-element', ShadowElement);
</script>
<shadow-element></shadow-element>

Note: Shadow DOM ensures style isolation. Use 'open' mode for JavaScript access.

5. Custom Elements

Custom elements extend HTML with user-defined tags, registered via customElements.define.

Example: Custom element with lifecycle callbacks.

<script>
class CustomElem extends HTMLElement {
connectedCallback() {
this.textContent = 'Custom Element Loaded';
}
}
customElements.define('custom-elem', CustomElem);
</script>
<custom-elem></custom-elem>

Note: Lifecycle callbacks allow reaction to element changes. Ensure unique tag names.

6. HTML Templates

The <template> tag holds reusable markup that is not rendered until cloned.

Example: Template cloning.

<template id="myTemplate">
<p>Template Content</p>
</template>
<script>
const template = document.getElementById('myTemplate').content.cloneNode(true);
document.body.appendChild(template);
</script>

Note: Templates are ideal for dynamic content generation. They are inert until cloned.

7. Slot Elements

Slots in shadow DOM allow insertion of external content into custom elements.

Example: Slotted content.

<script>
class SlottedElement extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({mode: 'open'});
shadow.innerHTML = '<slot>Default Slot</slot>';
}
}
customElements.define('slotted-element', SlottedElement);
</script>
<slotted-element>Slotted Content</slotted-element>
Slotted Content

Note: Named slots allow targeted content insertion. Enhances component flexibility.

8. Advanced Form Validation with Constraint API

The Constraint Validation API allows programmatic form validation using methods like checkValidity().

Example: Custom validation check.

<form>
<input type="email" id="email" required>
<button type="button" onclick="validateForm()">Validate</button>
</form>
<script>
function validateForm() {
const input = document.getElementById('email');
if (!input.checkValidity()) {
alert(input.validationMessage);
} else {
alert('Valid!');
}
}
</script>

Note: Use setCustomValidity for custom error messages. Improves form UX.

9. HTML5 Offline Cache (Manifest)

The manifest attribute in <html> enables offline caching via appcache (deprecated, but useful for legacy).

Example: App cache manifest.

<html manifest="cache.manifest">
<body>
<p>Offline-enabled page.</p>
</body>
</html>
<!-- cache.manifest content:
CACHE MANIFEST
# v1
index.html
styles.css -->

(App cache is not demonstrable here, but enables offline access.)

Note: Migrate to Service Workers for modern offline support. Appcache is deprecated.

10. Service Workers Integration

Service Workers act as proxy servers for offline caching and push notifications.

Example: Registering a service worker.

<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then(() => {
console.log('Service Worker Registered');
});
}
</script>
<!-- sw.js content:
self.addEventListener('install', e => { e.waitUntil(caches.open('cache').then(cache => cache.addAll(['/']))); });
self.addEventListener('fetch', e => { e.respondWith(caches.match(e.request).then(res => res || fetch(e.request))); });
-->

(Service Worker registration is not executable here, but enables offline functionality.)

Note: Service Workers require HTTPS. Use for PWA development.

11. Push Notifications Setup

Push notifications use Service Workers to deliver messages even when the app is closed.

Example: Push subscription.

<script>
navigator.serviceWorker.ready.then(sw => {
sw.pushManager.subscribe({userVisibleOnly: true, applicationServerKey: 'your_public_key'}).then(sub => console.log('Subscribed'));
});
</script>

(Push notifications require Service Worker and server setup, not demonstrable here.)

Note: Obtain user permission and use VAPID keys for security. Enhance user engagement.

12. Advanced Canvas Rendering

Advanced canvas techniques include gradients, transformations, and compositing for complex graphics.

Example: Gradient fill.

<canvas id="canvas" width="200" height="100"></canvas>
<script>
let ctx = document.getElementById('canvas').getContext('2d');
let gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, 'red');
gradient.addColorStop(1, 'blue');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 200, 100);
</script>

Note: Use requestAnimationFrame for smooth animations. Canvas is powerful for games and visualizations.

13. Canvas Path2D

Path2D allows creating reusable paths for canvas drawing, improving performance.

Example: Reusable path.

<canvas id="canvas" width="200" height="100"></canvas>
<script>
let ctx = document.getElementById('canvas').getContext('2d');
let path = new Path2D();
path.rect(50, 25, 100, 50);
ctx.fillStyle = 'green';
ctx.fill(path);
</script>

Note: Path2D can be reused and transformed. Useful for complex shapes.

14. SVG Animation with SMIL

SMIL (Synchronized Multimedia Integration Language) animates SVG elements without JavaScript.

Example: Animated circle.

<svg width="100" height="100">
<circle cx="50" cy="50" r="40" fill="blue">
<animate attributeName="r" from="40" to="10" dur="3s" repeatCount="indefinite"/>
</circle>
</svg>

Note: SMIL support is limited in some browsers; consider CSS or JS alternatives. Great for simple animations.

15. SVG Filters

SVG filters apply effects like blur or color shifts to graphics.

Example: Blur filter.

<svg width="100" height="100">
<defs>
<filter id="blur">
<feGaussianBlur stdDeviation="5"/>
</filter>
</defs>
<circle cx="50" cy="50" r="40" fill="blue" filter="url(#blur)"/>
</svg>

Note: Filters can be complex; test performance. Useful for visual effects.

16. HTML5 WebSockets Basics

WebSockets enable real-time bidirectional communication between client and server.

Example: WebSocket connection.

<script>
const socket = new WebSocket('ws://example.com/socket');
socket.onmessage = event => console.log('Message: ' + event.data);
socket.onopen = () => socket.send('Hello Server');
</script>

(WebSocket requires a server; logs messages in console.)

Note: Use wss:// for secure connections. Ideal for chat apps or live updates.

17. WebRTC Integration

WebRTC enables real-time communication like video calls directly in browsers.

Example: Basic video stream.

<video id="video" autoplay></video>
<script>
navigator.mediaDevices.getUserMedia({video: true}).then(stream => {
document.getElementById('video').srcObject = stream;
});
</script>

Note: Requires user permission and HTTPS. Use for peer-to-peer apps.

18. Advanced Drag and Drop with DataTransfer

Advanced drag-and-drop uses DataTransfer to pass custom data during drag events.

Example: Dragging with data.

<div draggable="true" ondragstart="event.dataTransfer.setData('text/plain', 'Dragged data')">Drag me</div>
<div ondrop="event.preventDefault(); alert(event.dataTransfer.getData('text/plain'))" ondragover="event.preventDefault()">Drop here</div>
Drag me
Drop here

Note: Support multiple MIME types for robustness. Enhance with keyboard alternatives.

19. HTML5 File API

The File API allows reading file contents from input fields for client-side processing.

Example: Reading file content.

<input type="file" id="fileInput">
<p id="fileContent"></p>
<script>
document.getElementById('fileInput').addEventListener('change', e => {
const file = e.target.files[0];
const reader = new FileReader();
reader.onload = ev => document.getElementById('fileContent').innerText = ev.target.result.substring(0, 100);
reader.readAsText(file);
});
</script>

Note: Handle large files carefully to avoid performance issues. Use for previews or uploads.

20. IndexedDB Basics

IndexedDB is a low-level API for client-side storage of structured data.

Example: Basic IndexedDB setup.

<script>
const request = indexedDB.open('myDB', 1);
request.onupgradeneeded = e => {
const db = e.target.result;
db.createObjectStore('store', {keyPath: 'id'});
};
request.onsuccess = e => {
const db = e.target.result;
const tx = db.transaction('store', 'readwrite');
tx.objectStore('store').add({id: 1, name: 'John'});
};
</script>

(IndexedDB operations are not visible but store data locally.)

Note: Use transactions for data integrity. Ideal for large datasets.

21. Advanced Microdata with Schema.org

Advanced microdata uses Schema.org vocabularies to add rich metadata for search engines.

Example: Product schema.

<div itemscope itemtype="http://schema.org/Product">
<span itemprop="name">Product Name</span>
<div itemprop="offers" itemscope itemtype="http://schema.org/Offer">
<span itemprop="price" content="10.00">$10.00</span>
</div>
</div>
Product Name
$10.00

Note: Validate with Google's Structured Data Testing Tool. Boosts SEO.

22. JSON-LD for Structured Data

JSON-LD embeds structured data in <script> tags for SEO and rich snippets.

Example: JSON-LD script.

<script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "Person",
"name": "John Doe",
"email": "[email protected]"
}
</script>

(JSON-LD is not visible but provides structured data for search engines.)

Note: Preferred format for structured data. Validate with tools like Google's.

23. HTML5 Content Security Policy Advanced

Advanced CSP uses nonces and hashes for inline scripts/styles to prevent XSS.

Example: CSP with nonce.

<meta http-equiv="Content-Security-Policy" content="script-src 'nonce-randomNonce'">
<script nonce="randomNonce">
console.log('Secure script');
</script>

(CSP with nonce secures inline scripts; not enforceable here.)

Note: Generate unique nonces per request. Enhances security.

24. HTTP/2 and HTML Integration

HTTP/2 enables multiplexing; use preload links in HTML for faster resource loading.

Example: Preload link.

<link rel="preload" href="styles.css" as="style">
<link rel="stylesheet" href="styles.css">

(Preload improves load times; not visible but optimizes performance.)

Note: Preload critical resources. Works best with HTTP/2.

25. Advanced Lazy Loading with Intersection Observer

Intersection Observer API enables lazy loading by detecting element visibility.

Example: Lazy load image.

<img data-src="image.jpg" alt="Lazy">
<script>
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.src = entry.target.dataset.src;
observer.unobserve(entry.target);
}
});
});
observer.observe(document.querySelector('img'));
</script>
Lazy

Note: Polyfill for older browsers. Improves performance on long pages.

26. HTML5 Picture-in-Picture

Picture-in-Picture (PiP) allows videos to float in a mini-window.

Example: PiP video.

<video id="video" controls>
<source src="video.mp4" type="video/mp4">
</video>
<button onclick="document.getElementById('video').requestPictureInPicture()">Enter PiP</button>

Note: Requires user gesture in some browsers. Enhances multitasking.

27. Media Capture API

The Media Capture API accesses device cameras and microphones for recording.

Example: Video capture.

<video id="video" autoplay></video>
<script>
navigator.mediaDevices.getUserMedia({video: true}).then(stream => {
document.getElementById('video').srcObject = stream;
});
</script>

Note: Requires HTTPS and user permission. Use for video calls or recording.

28. Vibration API

The Vibration API triggers device vibration for haptic feedback.

Example: Vibration button.

<button onclick="navigator.vibrate(200)">Vibrate

Note: Works on mobile devices. Use patterns for complex vibrations.

29. Battery Status API

The Battery Status API provides information about the device's battery level and charging status.

Example: Battery info.

<p id="battery"></p>
<script>
navigator.getBattery().then(battery => {
document.getElementById('battery').innerText = `Level: ${battery.level * 100}%, Charging: ${battery.charging}`;
});
</script>

Note: Listen to events for updates. Useful for power-aware apps.

30. Ambient Light Sensor API

The Ambient Light Sensor API detects light levels to adjust UI (e.g., dark mode).

Example: Light sensor.

<p id="light"></p>
<script>
const sensor = new AmbientLightSensor();
sensor.onreading = () => {
document.getElementById('light').innerText = `Illuminance: ${sensor.illuminance} lux`;
};
sensor.start();
</script>

Note: Requires permission. Use for adaptive UIs.

31. Advanced Accessibility with ARIA Live Regions

ARIA live regions announce dynamic content changes to screen readers.

Example: Polite live region.

<div aria-live="polite" id="status">Status: Ready</div>
<button onclick="document.getElementById('status').innerText = 'Status: Updated'">Update Status</button>
Status: Ready

Note: Use "assertive" for urgent updates. Test with screen readers.

32. ARIA Treegrid

ARIA treegrid role creates accessible hierarchical data grids.

Example: Treegrid table.

<table role="treegrid">
<tr role="row" aria-level="1" aria-expanded="true">
<td role="gridcell">Parent</td>
</tr>
<tr role="row" aria-level="2">
<td role="gridcell">Child</td>
</tr>
</table>
Parent
Child

Note: Use aria-expanded for collapsible rows. Ensures keyboard navigation.

33. HTML5 Fullscreen API

The Fullscreen API allows elements to enter fullscreen mode.

Example: Fullscreen button.

<video id="video" controls>
<source src="video.mp4" type="video/mp4">
</video>
<button onclick="document.getElementById('video').requestFullscreen()">Fullscreen</button>

Note: Handle fullscreenchange events. Works in most modern browsers.

34. Pointer Lock API

The Pointer Lock API locks the mouse pointer for immersive experiences like games.

Example: Pointer lock.

<div id="canvas" style="width:200px; height:100px; background:#f0f0f0;" onclick="this.requestPointerLock()">Click to lock pointer</div>
<script>
document.addEventListener('pointerlockchange', () => {
if (document.pointerLockElement) {
console.log('Pointer locked');
}
});
</script>
Click to lock pointer

Note: Requires user gesture. Use mousemove for controls.

35. Gamepad API

The Gamepad API detects and reads input from game controllers.

Example: Gamepad detection.

<p id="gamepad"></p>
<script>
window.addEventListener('gamepadconnected', e => {
document.getElementById('gamepad').innerText = `Gamepad connected: ${e.gamepad.id}`;
});
</script>

Note: Poll gamepad state in animation loop. Supports multiple controllers.

36. HTML5 Clipboard API

The Clipboard API allows reading and writing to the clipboard asynchronously.

Example: Copy text to clipboard.

<button onclick="navigator.clipboard.writeText('Copied text').then(() => alert('Copied!'))">Copy

Note: Requires HTTPS. Handle permissions and errors.

37. Speech Synthesis API

The Speech Synthesis API converts text to speech using browser voices.

Example: Text to speech.

<button onclick="speak('Hello, world!')">Speak

Note: Customize rate, pitch, and voice. Enhances accessibility.

38. Speech Recognition API

The Speech Recognition API transcribes spoken words to text.

Example: Voice to text.

<button onclick="startRecognition()">Start Recognition</button>
<p id="transcript"></p>
<script>
function startRecognition() {
const recognition = new webkitSpeechRecognition();
recognition.onresult = e => document.getElementById('transcript').innerText = e.results[0][0].transcript;
recognition.start();
}
</script>

Note: Prefix may vary (webkit). Requires permission; use for voice inputs.

39. Web Share API

The Web Share API allows sharing content via native share dialogs.

Example: Share button.

<button onclick="navigator.share({title: 'Share Title', text: 'Share Text', url: 'https://example.com'})">Share</button>

Note: Requires HTTPS. Enhances social sharing.

40. Payment Request API

The Payment Request API simplifies payment processing with native UI.

Example: Basic payment request.

<button onclick="makePayment()">Pay</button>
<script>
function makePayment() {
const request = new PaymentRequest([ {supportedMethods: 'basic-card'} ], {total: {label: 'Total', amount: {currency: 'USD', value: '10.00'}}});
request.show().then(response => response.complete('success'));
}
</script>

Note: Supports various payment methods. Requires secure context.

Macro Nepal is dedicated to mastering the art of coding and technology education. Our mission is to empower the next generation of tech talents in Nepal and beyond by providing comprehensive tools and resources for their success.

Follow Us

Terms & Conditions

Macro Nepal Helper