Loading Developer Playground

Loading ...

Skip to main content
ARIA ROLELive Region Roles

alert

A type of live region with important, and usually time-sensitive, information. Alert messages are announced immediately to screen readers, interrupting current speech.

Implicit aria-live
assertive
Implicit aria-atomic
true
Required Attributes
None

Overview

The alert role is used for important, time-sensitive messages that require the user's immediate attention. It creates a live region with aria-live="assertive" behavior.

Unlike other live regions, alerts interrupt the screen reader immediately to announce the message. Use this role sparingly - only for critical information like errors, warnings, or urgent notifications.

Alert vs Status

Use role="alert" for urgent messages that need immediate attention. Use role="status" for less urgent advisory information that can wait for a natural pause.

Live Demo: Alert Messages

Note: When you click a button, the alert will be announced immediately by screen readers, interrupting any current speech. This demonstrates the aria-live="assertive" behavior.

Implicit Attributes

The alert role automatically sets these attributes:

aria-live="assertive"

Alerts interrupt immediately. Screen readers stop current speech to announce the alert message.

aria-atomic="true"

The entire alert region is announced as a single unit, providing full context.

Code Examples

Basic Alert

<!-- Basic Alert -->
<div role="alert">
  <p>Error: Unable to save your changes. Please try again.</p>
</div>

<!-- Implicit aria-live="assertive" means this interrupts immediately -->

Form Validation

<!-- Form Validation Alert -->
<form id="login-form">
  <label for="email">Email</label>
  <input type="email" id="email" aria-describedby="email-error" />
  
  <!-- Alert appears when validation fails -->
  <div id="email-error" role="alert" style="display:none;">
    Please enter a valid email address
  </div>
</form>

<script>
  form.addEventListener('submit', (e) => {
    const email = document.getElementById('email');
    const error = document.getElementById('email-error');
    
    if (!email.value.includes('@')) {
      e.preventDefault();
      error.style.display = 'block';
      // Screen reader immediately announces the error
    }
  });
</script>

Dynamic Alert Messages

<!-- Dynamic Alert Messages -->
<div id="alert-container" role="alert" aria-atomic="true">
  <!-- Messages will be injected here -->
</div>

<script>
  function showAlert(message, type) {
    const container = document.getElementById('alert-container');
    
    // Update alert content
    container.innerHTML = `
      <div class="alert alert-${type}">
        <span class="icon" aria-hidden="true">
          ${type === 'error' ? '⚠️' : type === 'success' ? '✓' : 'ℹ️'}
        </span>
        <span>${message}</span>
      </div>
    `;
    
    // Auto-clear after 5 seconds
    setTimeout(() => {
      container.innerHTML = '';
    }, 5000);
  }
  
  // Usage
  try {
    await saveData();
    showAlert('Data saved successfully!', 'success');
  } catch (error) {
    showAlert('Failed to save data', 'error');
  }
</script>

React Component

// React Alert Component
import { useState, useEffect } from 'react';

function Alert({ message, type, onClose }) {
  useEffect(() => {
    if (message) {
      // Auto-dismiss after 5 seconds
      const timer = setTimeout(onClose, 5000);
      return () => clearTimeout(timer);
    }
  }, [message, onClose]);
  
  if (!message) return null;
  
  return (
    <div
      role="alert"
      aria-atomic="true"
      className={`alert alert-${type}`}
    >
      <span className="icon" aria-hidden="true">
        {type === 'error' && '⚠️'}
        {type === 'success' && '✓'}
        {type === 'info' && 'ℹ️'}
      </span>
      <span>{message}</span>
      <button 
        onClick={onClose}
        aria-label="Dismiss alert"
      >
        ×
      </button>
    </div>
  );
}

// Usage in parent component
function App() {
  const [alert, setAlert] = useState({ message: '', type: '' });
  
  const handleSave = async () => {
    try {
      await saveData();
      setAlert({
        message: 'Changes saved successfully!',
        type: 'success'
      });
    } catch (error) {
      setAlert({
        message: 'Failed to save changes',
        type: 'error'
      });
    }
  };
  
  return (
    <div>
      <Alert
        message={alert.message}
        type={alert.type}
        onClose={() => setAlert({ message: '', type: '' })}
      />
      
      <button onClick={handleSave}>Save</button>
    </div>
  );
}

Best Practices

Use for critical errors that need immediate attention

Use for time-sensitive warnings (session timeout, connection lost)

Keep alert messages concise and actionable

Include visual indicators (icons, colors) for sighted users

Auto-dismiss alerts after a reasonable time (5-10 seconds)

Provide a way to manually dismiss alerts

×

Don't use for success messages - use role="status" instead

×

Don't use for non-urgent information

×

Don't create multiple simultaneous alerts

×

Don't use alerts for progress updates or routine status changes

Common Use Cases

Form validation errors
Connection lost warnings
Session timeout alerts
Critical system errors
Security warnings
Data loss prevention
File upload failures
Payment processing errors

Accessibility Notes

Immediate Interruption

Alerts have aria-live="assertive" implicitly set, which means they interrupt the screen reader immediately. If a user is reading content, that speech will stop and the alert will be announced. Use this power responsibly.

Empty Alert Containers

You can create an empty alert container that's hidden until needed. When you add content to it, the alert will be announced. Make sure the container exists in the DOM before the alert is triggered for reliable announcements.

No Focus Change

Unlike alertdialog, the alert role doesn't move focus or require user interaction. It's simply announced and remains on screen. If you need to require user acknowledgment, use alertdialog instead.

Related Roles

Specifications & Resources