MediaWiki:Gadget-vector-headanchor.js

From wikiNonStop
Jump to navigation Jump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
/*!
 * Vector HeadAnchors gadget
 *
 * Copyright 2013 Timo Tijhof, https://mediawiki.org/wiki/MediaWiki:Gadget-vector-headanchor.js
 * SPDX-License-Identifier: MIT
 * License: https://opensource.org/licenses/MIT
 */

mw.hook( 'wikipage.content' ).add( function ( $content ) {
	$content.find( 'div.mw-heading' ).each( function ( i, heading ) {
		var el = heading.querySelector( '[id]:is(h1,h2,h3,h4,h5,h6)' );
		if ( !el || heading.querySelector( '.tpl-vheadanchor') ) {
			// No anchor possible, or anchor already inserted
			return;
		}
	
		// Support legacy Parser (wgParserEnableLegacyHeadingDOM=false):
		// <div class=mw-heading><h2 id>Headline</h2></div>
		//
		// Support Parsoid:
		// <section>
		//   <div class=mw-heading><h2 id>Headline</h2></div>
		// </section>
		//
		// Support DiscussionTools:
		// - DiscussionTools wraps H2 into DIV.mw-heading, setting overflow:hidden on
		//   the outer DIV instead of H2. Our override has to match to avoid clipping
		//   the anchor.
		// - DiscussionTools inserts an element with [id] before H2, so the above selector
		//   for `el` must hardcode all heading tags instead of just [id].
		// <div class=mw-heading>
		//   <span id="ooui-php-1" class="ext-discussiontools-init-section-subscribeButton"><a href>Subscribe</a></span>
		//   <h2 id><span>…</span>Headline<span>…</span></h2>
		// </div>
		heading.classList.add( 'tpl-vheadanchor-heading' );
	
		// Insert anchor.
		anchor = document.createElement( 'a' );
		anchor.href = '#' + el.id;
		anchor.textContent = '#';
		anchor.title = 'Link to this section';
		anchor.className = 'tpl-vheadanchor';
		heading.insertBefore( anchor, el.nextSibling );
	} );
} );