Lately, we’ve seen plugins for everything but as usual, when we find one that’s simple without purpose except making your page sluggish, we’ll write our own version, using 4 lines of jQuery! There’s no reason to use plugins for toggles, tabs or other simple elements when you can make yourself.
Necessary resources:
For this one, you’ll need jQuery and a pack of icons, for our example we used IonIcons
Step 1: The HTML Markup
<div class="accordion-item"> <a href="#" class="accordion-toggle">Is it super easy to build? <i class="ion-android-add"></i></a> <div class="accordion-content "> Just 4 lines of JS and 4 Lines of HTML and a bit of CSS </div> </div>
The HTML markup is again simple and contains just the necessary elements to help us obtain the structure we’re looking for
The first line will generate a wrapper to differentiate each individual accordion item for easier targeting using jS.
The second line will be the actual title of the content and the icon used to show some effects for opening and closing
The third line will be the content, you can add whatever you want here, we just added some text
The last line will close the individual toggle item. If you wish to create another one, simply duplicate these 4 lines.
.accordion-toggle{ height:50px; line-height:50px; font-size:15px; font-weight:600; padding-left:20px; } .accordion-toggle i{ font-size:18px; height:50px; width:50px; line-height:50px; padding:0px; text-align:center; position:absolute; right:10px; transition: all 250ms ease; } .accordion-content{display:none; padding:0px 20px 10px 20px;} .rotate-135{ transform: rotate(135deg); transition:all 250ms ease; }
With the style we’re defining the toggle button and the icon to the right side. The content of the toggle will be set to hidden and the right, bottom and left paddings set. We also use the rotate class to show the icon spinning when clicking it.
Now, let’s get to the last step!
Step 4: The jQuery
$('.accordion-item').click(function(){ $(this).find('.accordion-content').slideToggle(250); $(this).find('i').toggleClass('rotate-135 color-red-dark'); return false; });
And this is the jQuery that will drive our toggle. And it’s function is extremely simple and to the point. The first line, targets the title, when that is clicked it will select it, and from it it will move to locate it’s accordion-content class and enable or disable it on a click and also, it will search for its icon and apply the rotation class to it to turn into an x.
Ending Words
Use it, abuse it, duplicate the markup and create however many items you wish. There’s no lag, no loading of extra plugins and no slowing down your page. It’s that easy!
Thanks, and don’t forget to subscribe to get more items, discounts, freebies and new item releases!