JavaScript: show and hide elements like jQuery

JavaScript: show and hide elements like jQuery

How to emulate the jQuery's show() and hide() methods with JavaScript.

jQuery provides the .hide() and .show() methods that allow us to create nice effects on elements. In JavaScript we can implement such methods with the aid of CSS transitions.

Before getting into the details of our solution, let's explain what happens when we use the jQuery's methods. When jQuery hides an element, the element's dimensions are scaled down and the CSS display property is set to none. Conversely, when jQuery shows an element, the element's dimension are put back to normal and the CSS display property is set to the original value for the selected element. This means that if the original value was block, the final value will be block again and if the original value was table, the final value will be table (block will break the layout in this case).

CSS transitions don't work with the display property: the effect of any change to this property will be immediate. For that reason we have to create a timeout before making the element's dimensions scale up or down with CSS transformations.

We start with the following CSS code:


#element {
	transform: scale( 0 ); /* Zeroes element's dimensions */
	transition: all 500ms linear;
	display: none; /* Hides the element */
}

#element.visible {
	transform: scale( 1 ); /* Scales up element's dimensions */
}

Here's the JavaScript code to show and hide the element:


(function() {
	document.addEventListener( "DOMContentLoaded", function() {
		var show = document.querySelector( "#show" ),
		    hide = document.querySelector( "#hide" ),
			element = document.querySelector( "#element" );
			
			show.addEventListener( "click", function() {
				element.style.display = "block";
			  setTimeout(function() {
				element.className = "visible";
			  }, 300);
				
			}, false);
			
			hide.addEventListener( "click", function() {
				element.style.display = "block";
				element.className = "";
			  setTimeout(function() {
				element.style.display = "none";
			  }, 300);
				
			}, false);

	});
	
})();

Demo

See the Pen JavaScript: show/hide elements by Gabriele Romanato (@gabrieleromanato) on CodePen.