jQuery/CSS/HTML || Simple Collapsible Accordion Panel
Accordion panels are a vertical stack of items. Each item can be “expanded” or “collapsed” to reveal the content associated with that item. There can be zero expanded items, or more than one item expanded at a time, depending on the configuration.
Using jQuery, the following is sample code which demonstrates how to display a simple collapsible accordion panel to the page.
This panel comes with a few basic features. Using data attributes, you can adjust the slide up and slide down speed, as well as the initial collapsed status. You can also specify either the entire row as selectable, or just the button.
REQUIRED KNOWLEDGE
jQuery - closest
jQuery - next
jQuery - find
JavaScript - stopPropagation
JavaScript - Events
Accordion Panel - What is it?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 |
<!-- // ============================================================================ // Author: K Perkins // Date: Jun 2, 2020 // Taken From: http://programmingnotes.org/ // File: SimpleCollapsibleAccordionPanel.html // Description: Demonstrates how to display a simple collapsible // accordion panel to the page. // ============================================================================ --> <!DOCTYPE html> <html> <head> <title>My Programming Notes Simple Collapsible Accordion Panel Demo</title> <style> /* Indicates that an element is collapsible and clickable. To make the entire row clickable, only add this class to the 'collapsible-header' element. To make just the button clickable, only add this class to the 'collapsible-button' element. */ .collapsible { cursor: pointer; } .collapsible-header { background-color: #d6d6d6; border-top-left-radius: 5px; border-top-right-radius: 5px; padding: 10px; position: relative; width: 600px; text-align: left; border-top: 0.5px solid #bfbfbf; box-sizing: border-box; } .collapsible-header-text { max-width: 90%; max-height: 20px; overflow: hidden; padding-left: 8px; display: inline-block; font-family: helvetica,arial,sans-serif; white-space: nowrap; text-overflow: ellipsis; } .collapsible-button { float:right; position: absolute; right: 0; margin-right: 15px; display: inline-block; font-family: Tahoma,helvetica,arial,sans-serif; } .collapsible-button:after { content: '\002B'; /* + */ } .expanded, .collapsible-header:hover { background-color: #a6a6a6; } .collapsible-button.expanded:after { content: "\2212"; /* - */ } .collapsible-button.expanded { background-color: inherit; } .collapsible-body { border: 1px solid #d8d8d8; border-top: unset; max-height: 380px; width: 600px; padding: 15px; padding-top: 0px; padding-bottom: 0px; text-align: left; overflow: auto; box-sizing: border-box; display: none; } .inline { display:inline-block; } .main { text-align:center; margin-left:auto; margin-right:auto; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <div class="main"> <div class="inline" style="margin: 10px;"> <!-- Collapsible 1 --> <div class="collapsible collapsible-header"> <div class="collapsible-header-text" > Sample Header! </div> <div class="collapsible-button"> </div> </div> <div class="collapsible-body" data-slideup="800" data-slidedown="100" data-expanded="true"> <!-- Specify the slide duration (in milliseconds), and if the row is initially expanded --> <p> You can adjust the slide up and slide down speed, as well as the initial expanded status with data attributes. </p> <p> You can specify either the entire row as selectable, or just the button, depending on where the 'collapsible' class declaration is placed. </p> </div> <!-- Collapsible 2 --> <div class="collapsible collapsible-header"> <div class="collapsible-header-text" > A Journey To Another World </div> <div class="collapsible-button"> </div> </div> <div class="collapsible-body"> <div style="text-align: center;"> <p> Cultivated who resolution connection motionless did occasional. Journey promise if it colonel. Can all mirth abode nor hills added. Them men does for body pure. Far end not horses remain sister. Mr parish is to he answer roused piqued afford sussex. It abode words began enjoy years no do no. Tried spoil as heart visit blush or. Boy possible blessing sensible set but margaret interest. Off tears are day blind smile alone had. </p> <p> Another journey chamber way yet females man. Way extensive and dejection get delivered deficient sincerity gentleman age. Too end instrument possession contrasted motionless. Calling offence six joy feeling. Coming merits and was talent enough far. Sir joy northward sportsmen education. Discovery incommode earnestly no he commanded if. Put still any about manor heard. </p> <p> Use securing confined his shutters. Delightful as he it acceptance an solicitude discretion reasonably. Carriage we husbands advanced an perceive greatest. Totally dearest expense on demesne ye he. Curiosity excellent commanded in me. Unpleasing impression themselves to at assistance acceptance my or. On consider laughter civility offended oh. </p> <p> Breakfast agreeable incommode departure it an. By ignorant at on wondered relation. Enough at tastes really so cousin am of. Extensive therefore supported by extremity of contented. Is pursuit compact demesne invited elderly be. View him she roof tell her case has sigh. Moreover is possible he admitted sociable concerns. By in cold no less been sent hard hill. </p> </div> </div> <!-- Collapsible 3 --> <div class="collapsible collapsible-header"> <div class="collapsible-header-text" > Tell Us About Yourself </div> <div class="collapsible-button"> </div> </div> <div class="collapsible-body"> <div style="padding: 10px;"> <input type="radio" id="male" name="gender" value="male" checked> <label for="male">Male</label><br /> <input type="radio" id="female" name="gender" value="female"> <label for="female">Female</label><br /> <input type="radio" id="na" name="gender" value="na"> <label for="na">Prefer Not To Say</label> </div> </div> </div> <div style="margin-top: 5px;"> Click a tab to try! </div> </div> <script> $(document).ready(function() { $(".collapsible").on('click', function(e) { e.stopPropagation(); animateCollapsible($(this)); }); // Initialize each row to its initial // opened/closed state, depending on user values $('.collapsible').each(function(index, element) { animateCollapsible($(this)); }); }); /** * FUNCTION: animateCollapsible * USE: Handles opening/closing of a collapsible accordion panel. * @param sender: JQuery element that raised the event that * is decorated with the 'collapsible' class tag. * @return: N/A. */ function animateCollapsible($sender) { if (!$sender || $sender.length < 1) { return; } // Set class and data attribute variable names const settings = { classNameExpanded: 'expanded', classNameHeader: '.collapsible-header', classNameBody: '.collapsible-body', classNameButton: '.collapsible-button', dataNameSlideUp: 'slideup', dataNameSlideDown: 'slidedown', dataNameExpanded: 'expanded', dataNameCurrentlyExpanded: 'isCurrentlyExpanded' }; // Find the collapsible header row // and make sure its found let $header = $sender.closest(settings.classNameHeader); if (!$header || $header.length < 1) { alert('Unable to find header row!'); return; } // Find the associated collapsible body text // and make sure its found let $body = $header.next(settings.classNameBody); if (!$body || $body.length < 1) { alert('Unable to find content body!'); return; } // Determine if the content should be expanded or not // Get the slide up/down speeds let slideUpDuration = $body.data(settings.dataNameSlideUp); let slideDownDuration = $body.data(settings.dataNameSlideDown); // Get the current collapsible status let isCurrentlyExpanded = $body.data(settings.dataNameCurrentlyExpanded); // If the current status hasnt been defined yet, use the user defined value if (null == isCurrentlyExpanded) { isCurrentlyExpanded = $body.data(settings.dataNameExpanded) // Assume the row is closed if the user did not define a value if (null == isCurrentlyExpanded) { isCurrentlyExpanded = false; } // Remove the delay if there is a user defined value // so the row is immediately opened/closed slideUpDuration = 0; slideDownDuration = 0; } else { // The status has been defined in the past. Change its state if (isCurrentlyExpanded) { isCurrentlyExpanded = false; } else { isCurrentlyExpanded = true; } } // Find the action button so we can change its icon let $button = $header.find(settings.classNameButton); // Update contents depending on if the row is expanded or not if (isCurrentlyExpanded) { // Mark the header row as 'active' $header.addClass(settings.classNameExpanded); // Change the button icon to '-' $button.addClass(settings.classNameExpanded); // Slide down the body $body.slideDown(slideDownDuration); } else { // Remove the header row as 'active' $header.removeClass(settings.classNameExpanded); // Change the button icon to '+' $button.removeClass(settings.classNameExpanded); // Slide up the body $body.slideUp(slideUpDuration); } // Save the expanded status $body.data(settings.dataNameCurrentlyExpanded, isCurrentlyExpanded); } </script> </body> </html><!-- // http://programmingnotes.org/ --> |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Leave a Reply