Skip to content

Instantly share code, notes, and snippets.

@patrickfox
Last active April 6, 2021 18:27
Show Gist options
  • Save patrickfox/ed600b3b38c2cfab2b11 to your computer and use it in GitHub Desktop.
Save patrickfox/ed600b3b38c2cfab2b11 to your computer and use it in GitHub Desktop.
/*
# announce_view_loaded
Requirements:
- An element with `data-page-title` whose:
- text content is the page title: `<h2 data-page-title="">About Us</h2>` -> "About Us" will be used
- value is the page title: `<h3 data-page-title="Real page title">Displayed Heading</h3>` -> "Real page title" will be used
- An announcer element with an ID of `a11y_announcer` - this element needs to be in the DOM at page load and left alone (e.g. not destroyed or moved)
const site_title = '{Your site's name/title} - ';
function announce_view_loaded() {
var page_title, page_title_el;
page_title_el = document.querySelector('[data-page-title]');
if (page_title_el !== null) {
page_title = page_title_el.getAttribute('data-page-title') || page_title_el.innerText;
page_title = page_title === 'true'? page_title_el.innerText : page_title;
} else {
page_title = 'page title not set';
}
return set_title(page_title);
};
function set_title(page_title) {
page_title = site_title + page_title;
document.title = page_title;
announce(page_title + ' page loaded', 'assertive');
};
var announce_timeout = null;
function announce(message, manners) {
var announcer, clear_announcer;
manners = manners || 'polite';
announcer = document.getElementById('a11y_announcer');
if (announcer) {
announcer.setAttribute('aria-live', 'off');
clear_announcer = function() {
announcer.innerHTML = '';
announce_timeout = null;
return announcer;
};
announcer.setAttribute('aria-live', manners);
announcer.innerHTML = message;
clearTimeout(announce_timeout);
announce_timeout = setTimeout(clear_announcer, 500);
return announcer;
} else {
alert('a11y_announcer not found');
}
};
export { announce_view_loaded }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment