Accessible show/hide content with jquery
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.
17.05.2008. 13:30
Fritz Desir said on 24.09.2008. 04:20
Question, how would you use this if you have two or more sections of text on the same page both of which requiring show/hide?
Any reply would be greatly appreciated.
Andy said on 24.09.2008. 09:10
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.
Recent Comments:
Page last (manually) updated: May 01, 2007.
Questions, comments, insults or praise? Have your say: