Exploring options for Expand/Collapse (HTML, JavaScript)
Parent page: Generating Test Reports
Today’s post is a little bit of a side mini-project within the test reports theme. What I wanted is to add more structure in test logs, but made it summarized. So I went to explore about simple approaches in that.
Very often, on static pages (without AJAX) the approach used is switching HTML blocks between visible and invisible state. I provide a couple of working examples below.
Example 1 – Table In a Table
<script type="text/javascript"> function ShowHide(obj){ var tbody = obj.parentNode.parentNode.parentNode.getElementsByTagName("tbody")[0]; var old = tbody.style.display; tbody.style.display = (old == "none"?"":"none"); } </script> <!-- th{ text-align: left; cursor: pointer; } table tbody tr td{ padding-left: 15px; } --> <table> <tbody> <tr> <td> <table> <thead> <tr> <th onclick="ShowHide(this)">Log</th> </tr> </thead> <tbody> <tr> <td>sub 1</td> </tr> <tr> <td> <table> <thead> <tr> <th onclick="ShowHide(this)">Sub 1</th> </tr> </thead> <tbody> <tr> <td> <table> <thead> <tr> <th onclick="ShowHide(this)">sub 1 1</th> </tr> </thead> <tbody> <tr> <td>sub 1 1 1</td> </tr> <tr> <td>sub 1 1 2</td> </tr> </tbody> </table> </td> </tr> <tr> <td>sub 2 2</td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <div> <a href="http://automation-beyond.com/chapters/tutorials/test-reports/">Home</a></div>
And here is the demo file to download: Collapse1
Example 2 – Unique Blocks Inside the Table
<script> function ShowHide(body_id){ var TBody TBody = document.getElementById(body_id); if(!TBody) return true; if (TBody.style.display=="none") { TBody.style.display="block" } else { TBody.style.display="none" } return true; } </script> <table> <tbody> <tr> <th onclick="ShowHide('1')">Area 1</th> </tr> </tbody> <tbody id="1"> <tr> <td>Test Note</td> </tr> <tr> <td>Test Note</td> </tr> </tbody> <tbody> <tr> <th onclick="ShowHide('2')">Area 2</th> </tr> </tbody> <tbody id="2" style="display: block;"> <tr> <td>Test Note</td> </tr> <tr> <td>Test Note</td> </tr> </tbody> </table> <div> <a href="http://automation-beyond.com/chapters/tutorials/test-reports/">Home</a></div>
And here is the demo file to download: Collapse2
2 responses to "Exploring options for Expand/Collapse (HTML, JavaScript)"
need source code for the javascript function ShowHide(‘n’)
[Albert’s reply. If you can’t see source code in-page, download working examples as static pages and view the source.]
very new to coding so trying javascript rather than jquery and this looks like code I’m trying to implement. In the two examples, what if you want the initial state of the table/div to be hidden? What needs to be changed.
[ Albert’s reply:
Hi Richard – When ‘display’ is set to ‘none’ the element is hidden. Use downloadable examples if you want to experiment. ]