Show/hide block on click in jQuery

A small note on how using css and jquery you can show / hide a block by clicking on its title.

For example, it has the following structure

<section>
	<div class="block_title">
		Заголовок
	</div>
	<div class="block_content">
		Контент
	</div>
</section>

We need to hide and display a new content block when clicking on the header + change the icon in the header.

Let's style the icon first

.block_title:after {
	content: '⯅';
	position: absolute;
	right: 10px;
}

.close_title:after {
	content: '⯆';
}

And now let's add a script that will hide / show content and at the same time add / remove a class to change the icon

(function($){
	$(document).ready(function() {
		$(".block_title").click(function() {
			$(this).parent().find(".block_content").toggle("slide", { direction: "up" }, 500);
			$(this).toggleClass("close_title");
		});
	});
})(jQuery);

 

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
The comment language code.