Skip to content
Gary Storey
TwitterGithub

Improving an Accordion script - Part 2

JavaScript, jQuery3 min read

In part one of this, I took and existing javascript file and did some quick updates and optimizations to improve the overall performance of the script. We reduced the number of selectors and removed the animation functions and put those into the CSS.

My teammate and I thought it would be a great idea to expand the concept of the script to make it a more generalized accordion script. And that is what we are going to do in this post.

So the first thing, I wanted to do was to convert the single function into an object with it's own namespace.

1var accordion = {
2 //our code will go here
3 };

To do this in the most effective manner I also realized we will need to break about our single function into multiple functions that concentrate on doing a single specific thing making it more DRY.

When I create a JavaScript object I tend to start using a singleton pattern with certain properties and methods. I also tend to wrap all the code up in an iife passing in any objects needed. In this case we definitely need to pass in jQuery. I tend to add the window and document object as well. I also pass in undefined but since I don't set a value it gets set to ( you guessed it ) undefined.

1( function ( $, window, document, undefined ) {
2 'use strict';
3 var accordion = {
4 // code here
5 };
6 }) ( jQuery, window, document )();

That's a good starting template. Now, let's get to work on our actual script. Since I tend to end up converting all the way to a full-fledged jQuery plugin, I tend to break my object up into different sub-objects or sections. This makes it easier for me later. In the original script, we cached our initial selector. That's still a good idea but we are going to go about it in an entirely different way. We will add a property to our object to hold this selection and call it in our init() method. Since we are doing that, let's also go ahead and abstract away our class names so we can change them if we need to and not need to change the actual functionality of the script. This is what I ended up with:

1var accordion = {
2
3 settings : {
4 selector : undefined,
5 classes : { // CSS class names used by the script
6 root : 'accordion',
7 item : 'accordion-item',
8 header : 'accordion-header',
9 content : 'accordion-content',
10 selected : 'accordion-expanded',
11 expandAll : 'accordion-expand-all',
12 collapseAll : 'accordion-collapse-all'
13 }
14 },
15
16 _ : { // private functions
17 setSelector : function () {
18 var acc = accordion.settings;
19 acc.selector = $('.' + acc.classes.root);
20 }
21 }
22
23 init : function() {
24 this._.setSelector();
25 }
26 };

See what we've done here? When the init() function is called it sets the selector property. But what is actually going to be selected is now in our settings object. That way we can change the class name in one place and no further modification to the code will be needed. I also went ahead and added all the other classes we need as well.

Yes, this is a lot more code than we needed previously ( var accordion = $('.accordion'); ). But it still executes just as fast and it has laid the groundwork for something a lot more flexable than before.

To initialze our script we just call it onload.

1$(function(){
2 accordion.init();
3 });

OK. We have our selection, what else do we need? Well, let's start with our click events. In this we will use jQuery's event delegation and just put a single click event on the accordion container <div>. From there, we will determine what was clicked and do the appropriate action.

So, let's create a private function for creating the click event and then call that in our init(); function.

1var accordion = {
2 settings : { // settings code from above here
3 // new setting to hold our events
4 events : 'click.accordion dblclick.accordion touchend.accordion'
5 },
6
7 _ : { // private functions
8 setSelector : function () {
9 //selector code from above here,
10 },
11 addEvents : function () {
12 var acc = accordion.settings;
13 acc.selector.on( acc.events, checkEvents( evt ) );
14 }
15 checkEvents : function ( evt ) {
16
17 var sel = accordion.settings.selector,
18 cls = accordion.settings.classes,
19 $this = $(evt.target), $p = $this.parent();
20
21 if ($this.hasClass('.' + cls.expandAll)) {
22 sel.find('.' + cls.expanded).removeClass('.' + cls.expanded);
23 }
24 if ($this.hasClass('.' + cls.collapseAll)) {
25 sel.find('.' + cls.collapsed).removeClass('.' + cls.collapsed);
26 }
27 if ($this.hasClass('.' + cls.header)) {
28 $p.toggleClass('.' + cls.expanded);
29 }
30 }
31 },
32
33 init : function() {
34 this._.setSelector();
35 this._.setEvents();
36 }
37 };

Now we have updated our accordion object with a single event and we can modify all of the event types through our settings. Notice the event type all end in .accordion. This namespaces our events and allows us to target them specifically. All in all, much better. The code functions the same as our previous script but is now using our settings object to determine what and where to activate.

Let's add a new public method to "destroy" our accordion object (basically just removing our events ) and call it a day. Since we have namespaced the events, we will only be removing those events. If any other events been added outside of our script, they will not be affected! Got to love that!

Our complete script looks like this now:

1( function ( $, window, document, undefined ) {
2 'use strict';
3 var accordion = {
4 settings : {
5 selector : undefined,
6 classes : { // CSS class names used by the script
7 root : 'accordion',
8 item : 'accordion-item',
9 header : 'accordion-header',
10 content : 'accordion-content',
11 selected : 'accordion-expanded',
12 expandAll : 'accordion-expand-all',
13 collapseAll : 'accordion-collapse-all'
14 },
15 events : 'click.accordion dblclick.accordion touchend.accordion'
16 },
17
18 _ : { // private functions
19 setSelector : function () {
20 var acc =accordion.settings;
21 acc.selector = $('.'+ acc.classes.root);
22 },
23 addEvents : function () {
24 var acc = accordion.settings;
25 acc.selector.on( acc.events, checkEvents( evt ) );
26 },
27 checkEvents : function ( evt ) {
28 var sel = accordion.settings.selector,
29 cls = accordion.settings.classes,
30 $this = $(evt.target), $p = $this.parent();
31
32 if ($this.hasClass('.' + cls.expandAll)) {
33 sel.find('.' + cls.expanded).removeClass('.' + cls.expanded);
34 }
35 if ($this.hasClass('.' + cls.collapseAll)) {
36 sel.find('.' + cls.collapsed).removeClass('.' + cls.collapsed);
37 }
38 if ($this.hasClass('.' + cls.header)) {
39 $p.toggleClass('.' + cls.expanded);
40 }
41 },
42
43 removeEvents : function() {
44 var acc = accordion.settings;
45 acc.selector.off( acc.events, accordion._.checkEvents( evt ) );
46 }
47 }, // end private methods
48
49 init : function() {
50 this._.setSelector();
51 this._.setEvents();
52 },
53
54 destroy : function() {
55 this._.removeEvents();
56 }
57 }; // end accordion object
58
59 }) ( jQuery, window, document )();
60
61 $(function() { accordion.init(); });
62
63 // later if we want to remove accordion functionality
64 // all we do is call:
65 // accordion.destroy();

In Part 3, we will go ahead and convert this to jQuery plugin. Converting it to an object first ( in my opinion ) makes it easier. We will move aways from the singleton pattern above and put our methods into the Object prototype.

'Til next time,

-G

© 2023 by Gary Storey. All rights reserved.