- // If theres no toggle link, add it to the last cell
- if ( !$toggle.length ) {
- $toggleLink = buildDefaultToggleLink().prependTo( $firstItem.eq( -1 ) );
+ // If the table has a caption, collapse to the caption
+ // as opposed to the first row
+ $caption = $collapsible.find( '> caption' );
+ if ( $caption.length ) {
+ $toggle = $caption.find( '> .mw-collapsible-toggle' );
+
+ // If there is no toggle link, add it to the end of the caption
+ if ( !$toggle.length ) {
+ $toggleLink = buildDefaultToggleLink().appendTo( $caption );
+ } else {
+ actionHandler = premadeToggleHandler;
+ $toggleLink = $toggle.on( 'click.mw-collapsible keypress.mw-collapsible', actionHandler );
+ }