Show and hide html elements with javascript

This is a simple javascript file that show and hide html elements by adding the css class “hide” or “show”.

View source code on Github

If javascript is disabled than all hidden elements show by default so the page is not reliant on javascript (progressive enhancement, I believe).


/**
 * Hide and show elements on page load
 *
 * Code modified from Stackoverflow answer here http://stackoverflow.com/a/196038
 */
document.addEventListener("DOMContentLoaded", function() {
				hideElement(document.getElementById("email"));
        //add more l
				
				function hideElement(e) {
	 if ( e.className.match(/(?:^|\s)show(?!\S)/) ) {
		//remove class
		e.className = e.className.replace( /(?:^|\s)show(?!\S)/g , '' );
		//add class
		e.className += " hide";
	 } 
				}
	 function showElement(e) {
	 if (e.className.match(/(?:^|\s)hide(?!\S)/)) {
		 //remove class
		e.className = e.className.replace( /(?:^|\s)hide(?!\S)/g , '' );
		//add class
		e.className += " show";
	 }
				}
}

Elements are hidden with the position property (rather than display: none) to ensure that they remain accessible to screen readers.


.hide {
 position: absolute !important;
 top: -9999px !important;
 left: -9999px !important;	
}