Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to truncate text but keep the original, untruncated text, accessible to screen readers?

I have text that may break onto multiple lines but should be truncated with an ... added to the end if the maximum character count is exceeded.

Example - Original text = A link to something Truncated text = A link ...

Is there a way to store the original text so that it is accessiable to screen readers? I have been looking into aria attributes but am not sure if those can help in this situation.

Here is a fiddle to my current code, but I do think it is very accessible: http://jsfiddle.net/9s57b/

Here is my HTML:

<a href="#" class="js-text">A link to something</a>

Here is my JavaScript:

var element = document.querySelector('.js-text'),
  // innerText for IE, textContent for other browsers
  text = element.innerText || element.textContent,
  textArray = text.split(''),
  textArrayLength = textArray.length,
  maxCharacterCount = 7,
  newText = ''; 

if (textArrayLength > maxCharacterCount) {
  for (var i = 0; i < maxCharacterCount; i++) {
    newText += textArray[i];
  }
}

element.innerHTML = newText + ' ...';
like image 385
Mdd Avatar asked Oct 15 '25 13:10

Mdd


1 Answers

To truncate text visually while preserving the full original text for screen readers, the best practice is to:

  1. Truncate the visible text using CSS or JavaScript.

  2. Expose the full original text to screen readers using the aria-label attribute.

    <a href="#" class="truncate-accessibly">A link to something</a>

    const maxCharacters = 7;
    const el = document.querySelector('.truncate-accessibly');
    const originalText = el.textContent;
    
    if (originalText.length > maxCharacters) {
      const truncatedText = originalText.slice(0, maxCharacters) + '...';
      el.textContent = truncatedText;
      el.setAttribute('aria-label', originalText); // screen readers read full text
    }



like image 135
Hamza Khan Avatar answered Oct 17 '25 12:10

Hamza Khan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!