Code: Displaying and Handling Code in Web Development

Master HTML code tags, pre tags, and JavaScript error handling to create robust web applications with proper code display and error management.

The HTML Code Tag: Inline Code Display

The <code> tag serves as the foundation for displaying code snippets within HTML documents. Introduced as a semantic HTML element, it tells browsers and assistive technologies that the enclosed text represents computer code. When rendered, browsers apply a monospace font family to the content, visually distinguishing code from regular text, making it immediately recognizable as code rather than prose GeeksforGeeks.

Inline Code Syntax and Usage

The basic syntax for the <code> element is straightforward. You wrap the code fragment within opening and closing tags, and the browser handles the presentation. Unlike block-level elements, <code> is inline, meaning it flows naturally within paragraphs and other text content. This makes it ideal for referencing small code snippets, function names, or variable names within explanatory text. The browser renders this markup by applying a monospace font, immediately signaling to readers that this is code.

<p>The <code>console.log()</code> function outputs messages to the browser console.</p>
<p>Use the <code>const</code> keyword to declare constants in JavaScript.</p>

Browser Rendering and Semantic Benefits

When browsers render the <code> element, they apply a monospace font family to distinguish code from regular text. This visual distinction helps developers quickly identify code within prose. Beyond visual styling, the semantic meaning of <code> provides significant accessibility benefits--screen readers announce the content as "code" rather than reading it as regular text, which helps visually impaired users understand the context MDN Web Docs.

Preserving Semantic Meaning

Using <code> rather than simply styling text with a monospace font provides meaningful semantic information that search engines and assistive technologies can interpret. The semantic approach also future-proofs your code, as properly marked-up content will benefit from new features and improvements as browsers and assistive technologies evolve. When you use <code>, you're declaring the purpose of the content within the document's structure, not just making the text look like code.

Code Element Characteristics

The <code> element preserves the semantic distinction between code and content but does not preserve whitespace--line breaks and multiple spaces are collapsed, just as they are in regular HTML text. This is an important distinction: for single words or short phrases like method names or variable references, <code> works perfectly. For multi-line code blocks, you need to combine it with the <pre> element, which we'll explore in the next section.

The element inherits its default styling from the browser's user agent stylesheet, which typically applies a monospace font and adjusts spacing. Modern web development often overrides these defaults with custom CSS to match the site's design system while maintaining the monospace font characteristic. This ensures code snippets are both visually consistent with the rest of the page and immediately recognizable as code.

Manual Styling Comparison

While you could manually style text with a monospace font using CSS, the <code> element provides semantic meaning that manual styling cannot replicate. Screen readers announce the content as "code" rather than reading it as regular text, and search engines can better interpret the document structure, potentially improving relevance for programming-related queries. The semantic approach also ensures your code blocks work with browser features, developer tools, and assistive technologies that specifically look for semantic markup. For more advanced techniques in creating accessible, well-structured web content, explore our web development services that prioritize semantic HTML and accessibility best practices.

The HTML Pre Tag: Preserving Preformatted Text

The <pre> element complements <code> by providing a way to display multi-line code blocks and other preformatted text. The "pre" in its name stands for "preformatted," indicating that the text within this element should be displayed exactly as written, preserving whitespace, line breaks, and special characters exactly as they appear in the source code MDN Web Docs.

How Preformatted Text Works

When you wrap content in <pre> tags, the browser switches to a monospace font and displays the text with all its original spacing intact. Multiple spaces remain as multiple spaces, line breaks create new lines, and tab characters create indentation. This behavior makes <pre> ideal for displaying code that relies on specific formatting, such as Python with its indentation-based block structure where the visual layout is essential to understanding the code.

<pre>
function greet(name) {
 return "Hello, " + name + "!";
}
</pre>

Without <pre>, the browser would collapse all the spaces and display the code as a single line, losing the visual structure that helps developers understand the code's logic and flow GeeksforGeeks.

Whitespace Preservation Behavior

The whitespace preservation behavior of <pre> extends beyond simple indentation. Tab characters are preserved, and sequences of spaces remain exactly as written. This is essential for languages where indentation defines structure (Python, for example) or where code alignment improves readability (config files, data tables, ASCII art). The browser treats the content as semantically preformatted, respecting the developer's intended layout.

Displaying Multi-Line Code Blocks

For multi-line code blocks, <pre> becomes essential. Code functions spanning multiple lines, JSON data structures, configuration files, and command-line examples all require the whitespace preservation that <pre> provides. Without it, even well-formatted source code would appear as a single unreadable line, stripping away the visual hierarchy that makes code comprehensible at a glance. Proper code display is a fundamental aspect of professional web development that enhances documentation readability and developer experience.

Combining Pre with Code Tags

For code display, the standard practice is to nest <code> within <pre>. This combination provides both the semantic meaning of the <code> element and the whitespace preservation of <pre>. The pattern <pre><code>...</code></pre> has become so common that many developers use it automatically without considering the individual roles of each element. The <pre> handles the layout and spacing, while <code> provides semantic meaning for screen readers and search engines.

<pre><code>
function calculateArea(width, height) {
 if (width <= 0 || height <= 0) {
 throw new Error("Dimensions must be positive");
 }
 return width * height;
}
</code></pre>

Modern CSS Alternatives to Deprecated Attributes

While the <pre> element supports the width attribute to suggest the preferred character count per line, this attribute is deprecated and has no effect in modern browsers. Similarly, the wrap attribute, also deprecated, provided a hint about text overflow behavior that browsers now ignore entirely. These attributes remain in the HTML specification for historical compatibility but should not be used in new development.

Modern CSS provides the tools that these deprecated attributes once attempted to offer. The white-space property controls how whitespace is handled, with values like pre, pre-wrap, and pre-line offering fine-grained control over text wrapping and line break behavior. For responsive code display, combining <pre> with CSS overflow properties like overflow-x: auto ensures code blocks adapt gracefully to different screen sizes while maintaining readability.

Accessibility Considerations

Accessibility considerations for <pre> content mirror those for images and diagrams. When code blocks represent visual diagrams or ASCII art, provide alternative text descriptions using ARIA attributes. The combination of <figure>, <pre> with role="img" and aria-label, along with <figcaption>, ensures that screen readers announce the content appropriately and that users understand what the code represents MDN Web Docs. This semantic approach ensures all users can access and understand your code examples regardless of their assistive technology.

Why Nesting Pattern Is Standard Practice

The <pre><code> nesting pattern is the standard because it combines the best of both elements. <pre> ensures the visual formatting and whitespace are preserved exactly as written, while <code> adds semantic meaning that helps assistive technologies and search engines understand the content. Together, they create accessible, well-structured code blocks that work consistently across all browsers and devices. This combination is supported by decades of browser implementations and remains the recommended approach for displaying code in web pages.

HTML Code Tag Example
1<p>The <code>console.log()</code> function outputs messages to the browser console.</p>2<p>Use the <code>const</code> keyword to declare constants in JavaScript.</p>

Event Code: Understanding Error Events in JavaScript

JavaScript provides a robust system for handling errors through events. When something goes wrong--whether loading a script, fetching data, or processing media--the browser fires error events that your code can listen for and respond to. Understanding how to work with these events is essential for creating resilient web applications that gracefully handle unexpected failures MDN Web Docs.

How the Error Event Works

The error event fires when a resource fails to load or cannot be processed. This applies to various types of resources: images that fail to download, scripts with syntax errors, stylesheets that cannot be fetched, and media files that are corrupted or unsupported. The event provides information about what went wrong, allowing your code to respond appropriately with fallback content, user notifications, or diagnostic logging.

const image = document.querySelector('img.user-avatar');
image.addEventListener('error', () => {
 console.error('Failed to load image:', image.src);
 image.src = '/images/default-avatar.png';
});

This pattern is common in production applications where user-generated content or external resources might become unavailable. When a user avatar fails to load--perhaps because the file was deleted or the URL is incorrect--the error handler sets a fallback image. Users see a placeholder instead of a broken image icon, maintaining a polished experience even when external resources fail MDN Web Docs.

Common Error Event Scenarios

Error events can be triggered by numerous scenarios in modern web applications. Network failures cause images, scripts, and stylesheets to fail loading. Corrupted files result in media playback errors. Cross-origin restrictions block resources that don't have proper CORS headers. Server errors (5xx responses) prevent resources from being served. User navigation away from pages interrupts media playback. Each scenario requires appropriate handling to maintain application stability and user experience. Implementing comprehensive error handling is a hallmark of professional JavaScript web development practices.

Error Event Properties and Behavior

Error events have specific characteristics that distinguish them from other event types. They are not cancelable, meaning you cannot prevent the default behavior or stop propagation. They also do not bubble up the DOM tree in the same way that many other events do. These behaviors reflect the nature of error handling: the error has already occurred, and the event's purpose is notification rather than intervention. Understanding these behaviors helps you design appropriate error handling strategies.

When an error event fires, the event object contains information about what failed. For many element types, the event.target property points to the element that encountered the error. For media elements like <audio> and <video>, a MediaError object provides more specific information about what went wrong, including numeric error codes that identify the category of failure MDN Web Docs.

addEventListener vs onerror

There are two primary ways to handle error events in JavaScript. The first uses addEventListener, which provides the most flexibility and is the recommended approach for modern code. The second uses the onerror event handler property, which is simpler but less powerful. The addEventListener approach allows multiple handlers for the same event, giving you flexibility in how you respond to errors--you might have one handler that logs errors for monitoring, another that displays user-friendly messages, and a third that sends error details to a tracking service.

// Modern approach with addEventListener
document.addEventListener('error', (event) => {
 console.log('An error occurred:', event.message);
});

// Alternative with onerror property
window.onerror = (message, source, lineno, colno, error) => {
 console.log('Window error handled:', message);
 return true; // Prevents default error reporting
};

With onerror, only one handler can be assigned at a time, which limits flexibility. For production applications, addEventListener is the recommended modern approach that enables modular, maintainable error handling architectures.

Best Practices for Error Event Handling

Effective error event handling requires anticipating potential failures and designing graceful fallbacks. Test your error handlers with simulated failures to ensure they work correctly before deployment. Provide alternative content when primary resources fail--default images, fallback scripts, and alternative media formats keep experiences smooth. Communicate clearly by translating technical errors into actionable guidance that helps users understand what to do next.

JavaScript Error Event Handler
1const image = document.querySelector('img.user-avatar');2image.addEventListener('error', () => {3 console.error('Failed to load image:', image.src);4 image.src = '/images/default-avatar.png';5});

Media Error Codes: Understanding Media Loading Failures

When working with audio and video in web applications, the MediaError API provides detailed information about what went wrong when media fails to load or play. The code property returns a numeric value identifying the type of error, while the message property provides human-readable details that help diagnose specific failure scenarios MDN Web Docs.

The Four Media Error Codes

The MediaError specification defines four distinct error codes, each representing a different category of failure. Understanding these codes helps you provide appropriate feedback to users and log meaningful information for debugging in production environments.

CodeConstantDescription
1MEDIA_ERR_ABORTEDFetching was aborted by user's request
2MEDIA_ERR_NETWORKNetwork error prevented successful fetch
3MEDIA_ERR_DECODEError while decoding the media resource
4MEDIA_ERR_SRC_NOT_SUPPORTEDMedia source is unsuitable

MEDIA_ERR_ABORTED (Code 1)

The first code, MEDIA_ERR_ABORTED, indicates that the fetching process was aborted by the user's request. This typically happens when a user navigates away from a page before media finishes loading, or when a script explicitly aborts a load operation. Unlike other errors, this one often represents expected behavior rather than a problem--users frequently start videos and then click away before playback begins. When handling this error, avoid showing error messages since the user's navigation away from the page is intentional.

MEDIA_ERR_NETWORK (Code 2)

The second code, MEDIA_ERR_NETWORK, signals that a network error prevented the media from being fetched successfully. This could result from a lost internet connection, a blocked URL (perhaps by a firewall or CORS policy), or a server that's temporarily unavailable. The media might have worked previously but became inaccessible due to network conditions. When handling network errors, provide user-friendly messages suggesting they check their connection and try again. Consider implementing retry logic with exponential backoff for transient network issues.

MEDIA_ERR_DECODE (Code 3)

The third code, MEDIA_ERR_DECODE, occurs when the media format is corrupted or the browser cannot decode the stream. Even if the file downloads successfully, something prevents the browser from playing it--perhaps an unsupported codec, a truncated file, or corruption during transfer. Decode errors indicate a format problem rather than a delivery problem. Handle this by suggesting the user try a different browser or device, or by attempting to load an alternative format if multiple versions of the media are available.

MEDIA_ERR_SRC_NOT_SUPPORTED (Code 4)

The fourth code, MEDIA_ERR_SRC_NOT_SUPPORTED, indicates that the media source itself is unsuitable for the current browser or device. This might happen with formats that the browser doesn't support, URLs that point to non-media content, or sources that don't provide the expected media type MDN Web Docs. This error often occurs when serving HEVC video to browsers that only support VP9, or when a CDN returns an incorrect content type header. Provide clear messaging about format compatibility and consider detecting browser capabilities before attempting to load media.

Handling Different Error Types

Each error type requires a different response strategy. Aborted errors should be handled silently without user notification. Network errors warrant connectivity messages and potential retry mechanisms. Decode errors suggest format incompatibility that may require offering alternative formats. Source not supported errors require explaining compatibility limitations. By tailoring your response to each error type, you provide users with actionable guidance while maintaining a professional application experience. Robust error handling is essential for delivering exceptional user experiences in modern web applications.

Implementing Media Error Handling

A complete media error handler checks the error code and responds appropriately for each scenario. This might mean showing a user-friendly message, attempting to load a different format, or gracefully degrading the experience to maintain application stability.

Accessing the MediaError Object

Media elements expose their error state through the error property, which is null when no error has occurred. When an error event fires, you can access this property to retrieve the MediaError object containing diagnostic information. The object provides both a numeric code property for programmatic handling and a message property with human-readable details for logging and debugging.

Switch-Case Handling Pattern

Using a switch statement to handle different error codes provides clear, readable code that maps each error type to its appropriate response. This pattern makes it easy to add new error types and keeps error handling logic organized. Each case handles a specific error scenario, allowing you to provide targeted responses for different failure modes.

User Communication Strategies

Translating technical error codes into user-friendly messages builds trust and reduces support requests. Instead of displaying "MEDIA_ERR_NETWORK:2," show "Unable to load this video. Please check your internet connection and try again." The user needs to know what to do next, not the technical details of what went wrong. For more technical users or in debugging contexts, you can log the detailed error information to the console while showing simplified messages to end users.

Fallback Strategies

Implementing fallback strategies improves resilience when primary media sources fail. For network errors, retry the request after a brief delay. For decode errors, attempt to load an alternative format if available. For unsupported source errors, provide links to download the media or use a transcoding service. The goal is to provide the best possible experience even when things go wrong.

Logging and Monitoring

Implement comprehensive logging to track error patterns and identify systemic issues. Log the error code, the media source URL, any available message, and the timestamp. Consider using an error tracking service that aggregates these reports so you can identify patterns--perhaps certain video formats consistently fail on certain browsers, or specific CDN URLs are problematic. This data informs both technical fixes and content decisions.

Code Example: Complete Media Error Handler

const video = document.querySelector('video');

video.addEventListener('error', () => {
 const error = video.error;

 switch (error.code) {
 case MediaError.MEDIA_ERR_ABORTED:
 console.log('Playback aborted by user');
 break;
 case MediaError.MEDIA_ERR_NETWORK:
 console.log('Network error - check connection');
 displayUserMessage('Unable to load video. Please check your connection.');
 break;
 case MediaError.MEDIA_ERR_DECODE:
 console.log('Decode error - format issue');
 displayUserMessage('This video format is not supported.');
 break;
 case MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:
 console.log('Source not supported');
 tryFallbackFormat();
 break;
 }

 console.error('Media error details:', error.message);
});

This complete error handling pattern provides different responses based on what went wrong, translating technical error codes into user-friendly guidance. Network errors suggest checking connectivity, while decode errors indicate format problems. The specific response depends on your application's needs, but the key principle remains the same: use the error code to understand the problem and respond appropriately MDN Web Docs.

Key Concepts for Code Display and Error Handling

Master these essential techniques for robust web development

Semantic HTML for Code

Use <code> and <pre> elements to provide semantic meaning and proper formatting for code snippets.

Error Event Handling

Implement comprehensive error handlers using addEventListener for flexible, maintainable error management.

Media Error Codes

Understand the four MediaError codes to diagnose and respond appropriately to media loading failures.

Graceful Fallbacks

Provide alternative content and user-friendly messages when errors occur to maintain positive user experiences.

Accessibility

Use ARIA attributes and semantic markup to ensure code snippets are accessible to all users.

Logging and Monitoring

Implement comprehensive logging to track error patterns and improve application reliability.

Best Practices for Error Handling

Robust error handling goes beyond catching errors--it involves anticipating potential problems and designing graceful fallbacks from the start. The investment in proper error handling pays dividends in user trust and application resilience, reducing support requests and maintaining professional presentation even when unexpected failures occur.

Anticipate Failures

Plan for what can go wrong before it happens. Test your error handlers with simulated failures to ensure they work correctly under realistic conditions. Consider all the ways resources might fail: network disruptions, server timeouts, corrupted files, unsupported formats, and user interruptions. Building comprehensive error handling into your architecture from the beginning is far more effective than adding it later.

Provide Graceful Fallbacks

When primary resources fail, have alternatives ready. Default images, fallback scripts, and alternative media formats keep experiences smooth and prevent broken visual presentations. For images, provide placeholder images. For scripts, implement fallback CDN sources. For media, serve multiple format options. These fallbacks should be transparent to users when they work and seamless when they activate.

Communicate Clearly

Technical error messages confuse users and erode trust. Translate errors into actionable guidance that helps users understand what to do next. Instead of "MEDIA_ERR_NETWORK:2," display "Unable to load this video. Please check your internet connection." The user needs to know what to do, not what technical error occurred. Save the detailed error information for logs and debugging.

Log Strategically

Capture enough information to diagnose problems without overwhelming logs. Include error codes, URLs, contextual information like user actions and device details. Use structured logging that makes it easy to search and filter errors. Consider using error tracking services that aggregate reports across your user base, helping you identify patterns that might indicate systemic issues requiring attention.

Test Thoroughly

Simulate network failures, corrupted files, and unsupported formats during testing to verify error handlers work correctly. Use browser developer tools to block network requests and test loading failures. Test with actual error conditions rather than relying solely on unit tests. Verify that fallback content displays correctly and user messages are clear and helpful.

Monitor Production

Use error tracking services to aggregate and analyze errors across your user base. Set up alerts for unusual error patterns that might indicate systemic issues. Review error logs regularly to identify recurring problems. Use the data to prioritize fixes--both technical improvements and content adjustments that reduce error frequency.

Build Resilient Applications

By applying these techniques thoughtfully--using semantic HTML for code display, implementing comprehensive error handlers, and providing graceful fallbacks--you create web experiences that work reliably across devices and conditions. The investment in proper error handling pays dividends in user trust and application resilience, transforming potential failures into opportunities to demonstrate professionalism and care for user experience. For teams looking to implement enterprise-grade error handling and resilient application architecture, our web development expertise can help you build robust, user-friendly applications.

Dynamic Script Loading with Error Handling
1function loadScript(src, fallbackSrc) {2 return new Promise((resolve, reject) => {3 const script = document.createElement('script');4 script.src = src;5 6 script.onload = () => resolve(script);7 script.onerror = () => {8 console.warn(`Failed to load ${src}, trying fallback`);9 if (fallbackSrc) {10 script.src = fallbackSrc;11 script.onload = () => resolve(script);12 script.onerror = () => reject(new Error('Both scripts failed'));13 } else {14 reject(new Error(`Script load failed: ${src}`));15 }16 };17 18 document.head.appendChild(script);19 });20}

Build Robust Web Applications with Professional Development

Our team specializes in creating resilient web applications with proper error handling, accessible code display, and exceptional user experiences.

Frequently Asked Questions

What's the difference between <code> and <pre>?

The <code> element is for inline code snippets and doesn't preserve whitespace. The <pre> element preserves all whitespace and is used for multi-line code blocks. They're often used together: <pre><code> for formatted, semantic code display.

How do I handle media errors in JavaScript?

Listen for the 'error' event on media elements. The event.target.error property contains a MediaError object with a code property (1-4) indicating the error type. Use switch/case to handle each code appropriately.

What are the four media error codes?

MEDIA_ERR_ABORTED (1) - aborted by user; MEDIA_ERR_NETWORK (2) - network error; MEDIA_ERR_DECODE (3) - decode error; MEDIA_ERR_SRC_NOT_SUPPORTED (4) - unsupported source.

Should I use addEventListener or onerror?

Use addEventListener for flexibility--you can attach multiple handlers. The onerror property is simpler but only allows one handler. addEventListener is the recommended modern approach.

How do I make code snippets accessible?

Use semantic elements (<code>, <pre>), provide context with surrounding text, consider ARIA labels for complex examples, and test with screen readers. Ensure sufficient color contrast for syntax highlighting.

Sources

  1. MDN Web Docs - HTML pre tag - Official HTML specification documentation for preformatted text elements
  2. GeeksforGeeks - HTML code tag - Practical examples and usage patterns for code elements
  3. MDN Web Docs - MediaError code property - Complete reference for media error codes and handling
  4. MDN Web Docs - HTMLMediaElement error event - API documentation for media element error handling patterns