Jump to content

User:Slakr/sectionlinks.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
//
// based off of [[User:The Voidwalker/alwaysEditSectionLink.js]]
//
var $mwHeadlines = $('.mw-headline');
if (mw.config.get('wgIsProbablyEditable') && $mwHeadlines.length) {
  var normalEditLink = $('#ca-edit').find('a').attr('href');
  var normalPermalink = $('#t-permalink').find('a').attr('href');
  $mwHeadlines.each(function(idx) {
    var $ele = $(this);
    var sectionKey = $ele.attr('id');
    var sectionNum = idx + 1;
    
    // Find its parent element (probably an <h*>)
    var $dParent = $ele.parent();

    // Then see if there's already an editsection.
    var $editsection = $dParent.find('.mw-editsection');
    if (!$editsection.length) {
      $editsection = $('<span>').addClass('mw-editsection').append(
      	$('<span>').addClass('mw-editsection-bracket').text('['),
      	$('<a>')
      	  .attr('href', normalEditLink + '&section=' + sectionNum)
      	  .attr('title', 'Edit section')
      	  .text('edit'),
      	$('<span>').addClass('mw-editsection-bracket').text(']')
      );
      $editsection.appendTo($dParent);
      $editsection = $dParent.find('.mw-editsection');
    }
    var $lastBracket = $editsection.find('.mw-editsection-bracket:last');

	var separator = ' ⋅ '; // Equivalent to &nbsp;&sdot;&nbsp;
    var $linkSection = $('<a>').attr('href', '#' + encodeURIComponent(sectionKey)).text('link');
    var $permaLinkSection = $('<a>').attr('href', normalPermalink + '#' + encodeURIComponent(sectionKey)).text('perm');
    $lastBracket.prepend(document.createTextNode(separator), $linkSection, document.createTextNode(separator), $permaLinkSection);
  });
}