JAVASCRIPT

Toggling Element Visibility and Accessibility Attributes

Toggle the visibility of a DOM element using CSS display property and manage accessibility via `aria-hidden` and `tabindex` for better user experience.

function toggleVisibility(elementId, buttonId) {
  const element = document.getElementById(elementId);
  const button = document.getElementById(buttonId);

  if (!element || !button) {
    console.error(`Element or button not found for IDs: ${elementId}, ${buttonId}`);
    return;
  }

  const isHidden = element.style.display === 'none';

  element.style.display = isHidden ? '' : 'none'; // Toggle display
  element.setAttribute('aria-hidden', isHidden ? 'false' : 'true'); // Toggle accessibility attribute

  // Make elements inside focusable/unfocusable based on visibility
  if (isHidden) {
    element.querySelectorAll('a, button, input, select, textarea').forEach(focusableElement => {
      focusableElement.removeAttribute('tabindex');
    });
  } else {
    element.querySelectorAll('a, button, input, select, textarea').forEach(focusableElement => {
      focusableElement.setAttribute('tabindex', '-1');
    });
  }

  button.textContent = isHidden ? 'Hide Content' : 'Show Content';
}

// Example Usage:
// HTML to go with this:
// <button id="toggleButton">Show Content</button>
// <div id="myContent" style="display: none;" aria-hidden="true">
//   <p>This content will be toggled.</p>
//   <a href="#">Focusable Link</a>
//   <button>Another Button</n// </div>

document.getElementById('toggleButton').addEventListener('click', () => {
  toggleVisibility('myContent', 'toggleButton');
});
How it works: This snippet provides a function to toggle the visibility of a DOM element. It manipulates the element's `style.display` property to show or hide it. Crucially, it also updates the `aria-hidden` attribute for screen readers, informing assistive technologies whether the content is currently visible or not. Additionally, it manages `tabindex` for focusable elements within the toggled content to prevent users from tabbing into hidden elements, ensuring a good accessibility experience.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs