Accessible show/hide content with jquery
Update: Show/hide multiple elements independently
I'm a big fan of jquery since I don't often need to write any javascript, but for the times I do it cuts out most of the hassle of accessing on page elements, using CSS selectors and really helps with an accessible approach.
I recently wanted a section of a page to be hidden by default, with a link for users to show and hide the section. It's basically for an advanced options section of a form. What I wanted was to avoid any changes to the HTML whatsoever. Fortunately, jquery allows us to append content before an element, hide an element when the DOM is ready, and we can use an if else in order to change the link text from show to hide. Nothing groundbreaking or especially hard to do, but certainly useful. The code will hide a div with the CSS id hide_this (#hide_this), of course, alter this to suit the element you want to toggle.
// this tells jquery to run the function below once the DOM is ready $(document).ready(function() { // choose text for the show/hide link var showText="Show the hidden text"; var hideText="Hide the text"; // create the toggle link $("#hide_this").before("<p><a href='#' id='toggle_link'>"+showText+"</a>"); // hide the content $('#hide_this').hide(); // capture clicks on the newly created link $('a#toggle_link').click(function() { // change the link text if ($('a#toggle_link').text()==showText) { $('a#toggle_link').text(hideText); } else { $('a#toggle_link').text(showText); } // toggle the display $('#hide_this').toggle('slow'); // return false so any link destination is not followed return false; }); });
Demo of the accessible show/hide code
With javascript disabled, this text is visible by default and there is no show/hide link.
Comments
Andy
Sun, 03/10/2013 - 20:58
Do you want both sections
Do you want both sections hidden simultaneously, or to have links that hide them separately?
It's easy enough to achieve both. The function could be modified slightly so that it accepts a parameter to determine which section to hide.
valerio
Sun, 03/10/2013 - 20:58
please notice an unpleasant
please notice an unpleasant css bug in IE. trying to fix that
Fabio Varesano
Sun, 03/10/2013 - 20:58
Looks like you have an
Looks like you have an unclosed p tag in before()
Ekendra
Sun, 03/10/2013 - 20:58
Really simple and easy to use
Really simple and easy to use, thanks.
Add new comment