Toggling divs with jQuery

This isn’t new, but I use it enough that I like to keep a basic snippet handy.

This does the following:

  • Hides div-1 and div-2 on page load.
  • Opens div-1 and closes div-2 when button-1 is clicked
  • Opens div-2 and closes div-1 when button-2 is clicked
$( document ).ready(function() {
	$('.div-1').hide();
	$('.div-2').hide();
	$('.button-1').click(function() {
		$('.div-1').slideDown();
		$('.div-2').slideUp();
	});
	$('.button-1').click(function() {
		$('.div-1').slideDown();
		$('.div-2').slideUp();
	});
});

See it in action below. Styling the buttons will be left as an exercise to the reader:

This is Div-1!!!

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tempus, mauris in sollicitudin commodo, eros mauris euismod arcu, eget faucibus enim tellus a turpis. Suspendisse malesuada interdum elit sit amet rutrum. Nam ut elit lobortis, lobortis nisi sed, tincidunt nibh. In consequat eleifend quam, vestibulum efficitur velit scelerisque nec. Quisque quis rutrum mauris, ut ultricies ipsum. Cras interdum ipsum in diam venenatis fermentum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec mollis tincidunt est vitae dapibus. Aenean cursus, ipsum ac pellentesque malesuada, mauris magna pretium nunc, eu mollis dolor ipsum sit amet felis. Vestibulum sed erat eu dolor condimentum viverra blandit sit amet mauris. In arcu nisi, sollicitudin a dui a, laoreet pellentesque libero.

Woah, this is Div-2!~!~!

Suspendisse bibendum sem vitae tellus maximus dictum. Nunc vestibulum tellus sem, sit amet efficitur ligula porta sed. Aliquam erat volutpat. Suspendisse in enim elementum, iaculis magna eu, placerat enim. Aliquam auctor ultricies ligula eleifend sodales. Vestibulum at leo leo. Praesent sollicitudin ipsum ut maximus malesuada.

If you copied this example and it isn’t working, make sure you gave the divs and buttons the correct classes and you included jQuery in your header:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
View more TIL posts