20 Dec

jQuery Accordion plugin for beginners

Accordions can be of a great use when you want to present various sections of data in a small amount of space. It makes a better user experience. Today I’m going to show you how to create a simple accordion plugin for website. This post will help beginners to build your first jquery plugin.

w3_accordion.js

(function ($) {

$.fn.w3Accordion = function () {
     $(".accordion div:nth-child(2)").fadeIn();
     $(".accordion h3:nth-child(1)").addClass('active');

  $(".accordion h3").click(function(){
  	$(this).next("div").slideToggle("slow").siblings("div:visible").slideUp("slow");
    $(this).toggleClass("active");
    $(this).addClass('active');
    $(this).siblings("h3").removeClass("active");
  });
		return this;
	};
})(jQuery);

Call ‘w3Accordion’ jQuery function and CSS stylesheet into example.html

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/w3_accordion.js"></script>
<script type="text/javascript">
$(document).ready(function(){  
$('.accordion').w3Accordion();
});
</script>
<link href="w3_accordion_style.css" rel="stylesheet" />

HTML part of example.html

<div id="container">
<div class="accordion">
  <h3>Heading 1</h3>
  <div>
  <p>Description Text 1</p>
  </div>
  <h3>Heading 2</h3>
  <div>
  <p>Description Text 2</p>
  </div>
  </div>
</div>

w3_accordion_style.css

body {
	background:#00AFF0;
	color: #333333;
	font-family: Century Gothic, sans-serif;
}
#container {
	margin:auto;
	width:550px;
}
.accordion {
	float:left;
	background:#fff;
	border-radius: 6px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.45);
	padding:8px;
	width:500px;
}
.accordion div {
	display:none;
	border: 1px solid #BCBCBC;
	padding: 8px;
}
.accordion h3 {
	border-radius: 6px;
	padding: 4px;
	margin-bottom: 4px;
	color:#fff;
	margin-top: 4px;
	font-size: 19px;
	background-color:#198CB6;
}
.accordion h3:hover {
	cursor:pointer;
	background-color:#EB69D8;
}
.accordion .active {
	background-color: #EB69D8;
}
.accordion p {
	font-size: 14px;
	line-height: 23px;
	margin: 0;
	padding: 0;
}
.accordion img {
	float: left;
	height: 200px;
	margin-right: 12px;
	width: 200px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.45);
}

I hope beginners will enjoy this post..

 

Sanju
Follow me

About Sanju

I’m Sanjunath.S from Mumbai, India. I like web technologies, traveling & history. I have 11+ years of experience in web technologies like HTML 5, CSS 3, JavaScript, Bootstrap, and PHP.




Pay with PayPal
Translate »