Hiding elements that require JavaScript without JavaScript
a year ago
- #Web Development
- #Progressive Enhancement
- #JavaScript
- The site aims to function well without JavaScript, but some elements may appear clunky when JavaScript is disabled.
- A 7-line (or one-liner) solution can hide JavaScript-dependent elements to prevent broken functionality for users with JavaScript off.
- Example: A share button shows an SVG when JavaScript is enabled and a link when disabled, using the `<noscript>` tag for the latter.
- Initial approach: Adding a `js-enabled` class via JavaScript in the `<head>` to style elements differently, but this felt clunky.
- Alternative solution: Using `<noscript>` with a `<style>` tag to hide specific elements (e.g., `.theme-toggle`, `.menu-trigger`) when JavaScript is disabled.
- Improved method: Introducing a single class `.d-js-required` to hide all JavaScript-dependent elements with minimal CSS, avoiding maintenance overhead.
- Conclusion: Creative solutions like these help manage progressive enhancement, ensuring a smooth experience regardless of JavaScript availability.