This is the workshop support page for the user script ViewAnnotationToggler.js. Comments and requests concerning the program are most welcome. Please post discussion threads below the section titled Discussions. Thank you. By the way, the various scripts I have written are listed at the bottom of the page.
This script is operational: its main features work; it is under further development

AnnotationToggler = Annotation Toggler. It adds a tab menu item to toggle list item (LI) annotations.

Script's workshop

This is the work area for developing the script and its documentation. The talk page portion of this page starts at #Discussions, below.

Description / instruction manual

This script is operational: its main features work; it is under further development

ViewAnnotationToggler.js: adds a tab menu item and hot key to turn list item annotations off and on, across all pages..

The hot key is ⇧ Shift+Alt+a.

This script works on the list items in bulleted lists, lists in which each item is preceded by a bullet. Bulleted lists abound upon Wikipedia. They are used in stand-alone lists which are entire articles that are lists, and they are used in embedded lists situated within articles.

Many list items have an annotation, that is, the list item is followed by a description. These descriptions are useful, but they may obscure the items in the list that they describe. Sometimes, it is useful to look at the bare list, without the annotations.

This script turns those descriptions on and off. It provides a tab menu command and a hotkey for doing so.

When you don't need to see the descriptions, turn them off. When you need more detail, hit the toggle again, and the descriptions return. The script stores its status so it doesn't start over between pages — when annotations are turned off, they are off for all pages until you turn them back on again.

How to install this script

Important: this script was developed for use with the Vector skin (it's Wikipedia's default skin), and might not work with other skins. See the top of your Preferences appearance page, to be sure Vector is the chosen skin for your account.

To install this script, add this line to your vector.js page:

importScript("User:The Transhumanist/ViewAnnotationToggler.js");

Save the page and bypass your cache to make sure the changes take effect. By the way, only logged-in users can install scripts.

Explanatory notes (source code walk-through)

This section explains the source code, in detail. It is for JavaScript programmers, and for those who want to learn how to program in JavaScript. Hopefully, this will enable you to adapt existing source code into new user scripts with greater ease, and perhaps even compose user scripts from scratch.

You can only use so many comments in the source code before you start to choke or bury the programming itself. So, I've put short summaries in the source code, and have provided in-depth explanations here.

My intention is Threefold:

  1. to thoroughly document the script so that even relatively new JavaScript programmers can understand what it does and how it works, including the underlying programming conventions. This is so that the components and approaches can be modified, or used again and again elsewhere, with confidence. (I often build scripts by copying and pasting code that I don't fully understand, which often leads to getting stuck). To prevent getting stuck, the notes below include extensive interpretations, explanations, instructions, examples, and links to relevant documentation and tutorials, etc. Hopefully, this will help both you and I grok the source code and the language it is written in (JavaScript).
  2. to refresh my memory of exactly how the script works, in case I don't look at the source code for weeks or months.
  3. to document my understanding, so that it can be corrected. If you see that I have a misconception about something, please let me know!

In addition to plain vanilla JavaScript code, this script relies heavily on the jQuery library.

If you have any comments or questions, feel free to post them at the bottom of this page under Discussions. Be sure to {{ping}} me when you do.

General approach

We prep the page by wrapping list item annotations in spans with the class "anno". Then we refer to that class later in hide and show functions which create a menu item that the user can click on. How we do all of this is explained in fine detail below.

aliases

An alias is one string defined to mean another. Another term for "alias" is "shortcut". In the script, the following aliases are used:

$ is the alias for jQuery

mw is the alias for mediawiki

These two aliases are set up like this:

( function ( mw, $ ) {}( mediaWiki, jQuery ) );

That is a "bodyguard function", and is explained in the section below...

Bodyguard function

The bodyguard function assigns an alias for a name within the function, and reserves that alias for that purpose only. For example, if you want "t" to be interpreted only as "transhumanist".

Since the script uses jQuery, we want to defend jQuery's alias, the "$". The bodyguard function makes it so that "$" means only "jQuery" inside the function, even if it means something else outside the function. That is, it prevents other javascript libraries from overwriting the $() shortcut for jQuery. It does this via scoping.

The bodyguard function is used like a wrapper, with the alias-containing source code inside it. Here's what a jQuery bodyguard function looks like:

1 ( function($) {
2     // you put the body of the script here
3 } ) ( jQuery );

See also: bodyguard function solution.

To extend that to lock in "mw" to mean "mediawiki", use the following (this is what the script uses):

1 ( function(mw, $) {
2     // you put the body of the script here
3 } ) (mediawiki, jQuery);

For the best explanation of the bodyguard function I've found so far, see: Solving "$(document).ready is not a function" and other problems

The ready() event listener/handler

The ready() event listener/handler makes the rest of the script wait until the page (and its DOM) is loaded and ready to be worked on. If the script tries to do its thing before the page is loaded, there won't be anywhere for it to place the menu item (mw.util.addPortletLink), and the script will fail.

In jQuery, it looks like this: $( document ).ready() {});

The part of the script that is being made to wait goes inside the curly brackets. But you would generally start that on the next line, and put the ending curly bracket, closing parenthesis, and semicolon following that on a line of their own), like this:

1 $(function() {<br>
2     // Body of function (or even the rest of the script) goes here, such as a click handler.<br>
3 });

This is all explained further at the jQuery page for .ready()

For the plain vanilla version see: http://docs.jquery.com/Tutorials:Introducing_$(document).ready()

Prep work

var

This is a reserved word (aka "keyword"). The keyword var is used to declare variables in variable statements. A variable is a container you can put a value in. To declare the variable portletlink, write this:

var portletlink

A declared variable has no value, until you assign it one. You can combine declaration and assignment, like this:

var portletlink = mw.util.addPortletLink('p-tb', '#', 'Annotations');

document.get.ElementById()

Part of the WWW's Document API, this method returns the element with the specified ID. That is, it fetches the entire contents of a unique element. (If the element ID is not unique, it'll fetch the first one only).

A key use of this method is to assign the contents of an element to a variable. (See below).

"mw-content-text"

mw-content-text is an element ID. Unlike classes, IDs are unique (or are supposed to be).

Unfortunately, this ID is not covered in WP:IDS.

But it is included in the list mw:Manual:Interface/IDs and classes:

It's the part of the HTML page (of a Wikipedia page) that "holds everything between the page title and contentSub on the one hand, and ArticleFeedback and categories on the other hand. present on each page view (includes history view, non-existing pages, print view, ...)."

cont.outerHTML

"cont" is a variable.

It is defined in the following statement:

var cont = document.getElementById('mw-content-text');

That assigned the contents of the page (the content ID'd as mw-content-text) to the variable.

cont.outerHTML refers to all of cont, including the tags it is enclosed in. That is, the whole element, not just its contents. This is useful when used with .replace, so that a regex can be used to match the tags in a document. (See next section, below).

outerHTML.replace

innerHTML.replace tells regex to search and replace only within the contents of elements, NOT including their tags.

outerHTML.replace tells regex to search and replace within all of the HTML, including the tags. That way, you can search for elements, and not just things inside the elements.

So, this statement in the script:

cont.outerHTML = cont.outerHTML.replace(/(<li>.*?)( –.*)/g,'$1<span class="anno">$2</span>');

Looks for strings with

  • tags in them. If we used innerHTML, it would not find any.

    Wrapping the annotations in span tags

    With this tactic, we isolate the annotations so that we can switch their display on and off later in the script. To isolate them, we wrap the desired content in span tags, with the span including a class. Once they all have the same class, we can manipulate them all at once (like hiding or showing them all).

    To do the wrap, we use regex via the .replace method, like this to insert span tags in the desired locations:

    cont.outerHTML = cont.outerHTML.replace(/(<li>.*?)( –.*)/g,'$1<span class="anno">$2</span>');
    

    The .outerHTML allows us to match the tags of elements, and not just the contents of elements. If we used .innerHTML, regex would not see the <li> tags, and we would have no way of finding the bulleted list items on the page.

    This approach is easier (and more elegant) than using regex to remove the annotations directly, because if you do it that way, you would need to save a copy of the whole page before you removed them, in order to get them back when you "toggle" them back on.

    Central control structure

    This part controls the main flow of the script (decides what to do under what circumstances):

    if ( mw.config.get( 'skin' ) === 'vector' ) {
        $( function() {
            var annostatus = localStorage.getItem('annostatus');
            if ( annostatus === "hide" ) {
                annoHide();
            } else {
                annoShow();
            }
        } );
    }
    

    So, what this does is 3 things:

    First, it checks if the Vector skin is being used and runs the rest of the script only if it is.

    Then it checks the status of the script, that is, whether it was set to "show" or "hide" the last time it was used.

    Then it calls the function that corresponds with the current status (calling either annoHide or annoShow, defaulting to annoShow if there is no status).

    if and if/else statements

    mw.config.get ( 'skin' )

    This looks up the value for skin (the internal name of the currently used skin) saved in MediaWiki's configuration file.

    logical operators

    === means "equal value and equal type"

    localStorage.getItem

    Calling a function

    In JavaScript, a function is a subroutine. You call a function by its name. The function "example" is called like this:

    example();
    

    See also: JavaScript Function Invocation.

    The script has 2 custom functions written in it: annoHide, and annoShow. Each one includes a function call to the other, but the main controlling structure of the program checks local storage to see what the program's hide/show status is (in local storage), and calls the corresponding function.

    Subroutines (functions)

    Defining a function

    "Function" is another name for "subroutine". Here's how you define a function in JavaScript:

    function nameoffunction() {
    // do some stuff here
    }
    

    The function itself (the instructions that are executed when the function is called) lies between the curly brackets.

    A function is not activated until it is called. (See next section).

    localStorage.setItem

    The localStorage property allows you to store some data in the browser's memory area for later use, so you don't lose it when changing pages or closing the browser.

    What we use it for in the script is to store the script's show/hide status, so we can check it (each time the script starts) to see whether the script is supposed to execute the annoHide or the annoShow function. To create a data item in localStorage named "annostatus" for storing the value "show", we do this:

    localStorage.setItem("annostatus", "show");
    

    To store the script's status as "hide", we do this:

    localStorage.setItem("annostatus", "hide");
    

    For further detail, see: Using the Web Storage API.

    How the script hides and shows the annotations

    The main power of the script is provided by using two jQuery methods: .hide and .show

    Each works on the elements that they are appended to. We append them to "anno", which is the class we assigned earlier to all annotations by wrapping them in span tags, but they must be appended in a specific way, like this:

    $( ".anno" ).hide();
    

    and this:

    $( ".anno").show();
    

    Checking and clearing the menu item

    After the script executes a show or hide, the menu item needs to be updated. The first step is to check that it ("annoSwitch") exists, and if it does, remove it. Like this:

    if ( annoSwitch ) {
        annoSwitch.parentNode.removeChild(annoSwitch);
    }
    

    I have no idea why you can't remove a node directly, instead of removing it as a child of its parentNode. That seems convoluted, but it is the only way I could find that worked. If you know of an easier (more direct) way, please let me know.

    mw.util.addPortletLink is a function in the core module "mediaWiki". It adds a menu item to one of Wikipedia's menus. Use "p-tb" to signify the toolbox menu on the sidebar menu.

    First you stick it in a variable, for example, "portletlink":

    var portletlink = mw.util.addPortletLink('p-tb', '#', 'Annotations \(show\)');
    

    It has up to 7 parameters, with the first 3 being required. Only those 3 are used above.

    Important: It won't do anything until you bind it to a click handler (see below).

    General usage:

    mw.util.addPortletLink( 'portletId', 'href', 'text', 'id', 'tooltip', 'accesskey', 'nextnode');
    

    It's components:

    • mw.util.addPortletLink: the ResourceLoader module to add links to the portlets.
    • portletId: portlet id— the section where the new menu item is to be placed. Valid values:
      • p-navigation: Navigation section in left sidebar
      • p-interaction: Interaction section in left sidebar
      • p-tb: Toolbox section in left sidebar
      • coll-print_export: Print/export section in left sidebar
      • p-personal Personal toolbar at the top of the page
      • p-views Upper right tabs in Vector only (read, edit, history, watch, etc.)
      • p-cactions Drop-down menu containing move, etc. (in Vector); subject/talk links and action links in other skins
    • href: Link to the Wikipedia or external page
    • text: Text that displays
    • id: HTML id (optional)
    • tooltip: Tooltip to display on mouseover (optional)
    • accesskey: Shortcut key press (optional)
    • nextnode: Existing portlet link to place the new portlet link before (optional)

    The optional fields must be included in the above order. To skip a field without changing it, use the value null.

    For the documentation on this function, see https://www.mediawiki.orghttps://wiki95.com/en/ResourceLoader/Modules#addPortletLink and Help:Customizing toolbars.

    Important: It won't do anything until you bind it to a click handler (see below).

    click handler

    To make the above menu item so it does something when you click on it, you have to "bind" it to a handler. Like this:

    1 $(portletlink).click( function(e) {
    2 e.preventDefault();
    3 //do some stuff
    4 }
    

    The "handler" is the part between the curly brackets.

    To read about function(e), see what does e mean in this function definition?
    jQuery's event objects are explained here: http://api.jquery.com/category/events/event-object/
    e.preventDefault() is short for event.preventDefault(), one of jQuery's event objects.

    Change log

    • 2016-12-08
      • Anchor regexes on <li> (starting only) element delimiters
      • Version 0.1 – Primary functionality completed - it does as intended: switches between having and not having annotations (Turns on and off, albeit per page)
        • Clones the page's state, to restore it after annotations are removed
        • Uses regex to remove annotations
        • Uses a toggle to switch back and forth between the two states
    • 2016-12-11
    • 2017-01-19
    • 2017-07-05
      • Added document ready function, so the script waits until the DOM is loaded before running
      • Changed menu items to "Annotations (show)" and "Annotations (hide)"
    • 2017-07-06
      • Moved the functions to the end of the script to make it easier to follow; marked the sections clearly
    • 2017-07-07
    • 2018-02-23
      • Changed name to ViewAnnotationToggler.js
      • removed activation filter so it works on all pages
    • 2018-03-13
      • Script editor wouldn't work while ViewAnnotationToggler was running, so added a deactivation filter so that this script doesn't run on edit pages.

    Task list

    Bug reports

    Desired/completed features

    Completed features are marked with  Done

    Improvements needed:

    • Don't run on move pages
    • Since it hides content, an indicator is needed to show when it is on/off.
    • Fix the conflict with sidebar toggle (it also uses hot-key Shift-Alt-a)
    • load mw:ResourceLoader/Modules#mediawiki.util
    • Test on many pages of every page type
    • Test on other browsers (tested on Firefox 43.0.4)
    • Port to GreaseMonkey
    • Have separate hot-keys for on and off, to be macro-friendly?
    • Convert annotations, and then clone? (then it will toggle with fixed format)
    • Feature to apply and save fixes (conversions) to wikicode (i.e., replace non-standard annotation punctuation in the page source)

    Have the viewport stay anchored on its top entry when the toggle is used

    Temporary fix for viewport problem: invisibility

    http://stackoverflow.com/questions/9614622/equivalent-of-jquery-hide-to-set-visibility-hidden

    It states: There isn't one built in but you could write your own quite easily:

    (function($) {
    
        $.fn.invisible = function() {
            return this.each(function() {
                $(this).css("visibility", "hidden");
            });
        };
        $.fn.visible = function() {
            return this.each(function() {
                $(this).css("visibility", "visible");
            });
        };
    }(jQuery));
    

    You can then call this like so:

    $("#someElem").invisible();
    $("#someOther").visible();
    

    Here's a working example.

    Find/replace annotations of other formats

    • regular hyphens
    • em dashes
    • no-break space-hyphen combos
    • commas
    • hanging hyphens (hyphen, with no annotation)
    • parenthetic annotations?
    • colons

    Find/replace annotations of lead list entries (without bullets)

    • Only on pages with the title "Outline of"
    • Match entry that follows heading
    • Match entry that follows "{{Main}}"?
    • While in hidden mode, have popup functionality for annotations, when the mouse cursor is hovered over:
      • The topic?
      • The bullet?

    Program on/off switch

    The current objective is to store global variables, and pass them on to the next page, including the current page upon refresh.

    The state of the program can then be controlled from page to page, via conditionals applied upon the global variables.

    Methods that persists data across a page refresh include:

    • iframe – ?
    • ajax – ?
    • cookies – this requires a server call, and is inefficient
    • localstorage
      • localStorage.setItem("annostatus", "hide");
        
      • var annostatus = localStorage.getItem('annostatus');
        

    Feature completed. The Transhumanist 09:06, 11 December 2016 (UTC)

    Went from cloning/regex-to-null to show/hide wrapper

    Initially, the program toggled hide/show in a rather convoluted way: first it saved the mw-content element by cloning it. Then it deleted the annotations using regex. To get them back, it made a clone of the clone, and then replaced mw-content with the second clone. Here's that version:

    https://en.wikipedia.org/w/index.php?title=User:The_Transhumanist/anno.js&oldid=759842909

    Then based on a suggestion by Anomie, I simplified the script to wrap each annotation in a classed span (class="anno"), and then used jQuery in the subfunctions to .hide and .show the class. Here's the simplification:

    https://en.wikipedia.org/w/index.php?title=User:The_Transhumanist/anno.js&oldid=760834841

    It shrank by several lines of code. The Transhumanist 13:27, 19 January 2017 (UTC)

    Development notes

    Trycatch needed, and more

    The Transhumanist, where you use local storage.getItem() or setItem() you should always wrap that in try catch, as it can fail at any moment (even if you checked previously). This can be due to the browser running out of storage space for the domain, or because the browser is running in privacy mode or with an ad blocker extensions or something. Also, your new RegExp() calls should be lifted outside of the for loops, so that they aren't continuously recreated. For wpTextbox1.value, realise that sometimes the content might be managed by an editor (The syntaxhighlighting beta does this for instance). We use the jquery.textSelection plugin to abstract way from these differences. Don't check document.title, check mw.config.get( 'wgTitle' ) or mw.config.get( 'wgPageName' ). And when you use mw.util.addPortlink, you have to ensure that the mediawiki.util plugin is loaded already, which you can do by using mw.loader.using. —TheDJ (talkcontribs) 14:47, 27 October 2017 (UTC)

    Injecting/inserting/embedding style

    One way to hide/show a class is to define that class on the page, and then toggle its display property. Where are the instructions on how to do this?

    Here are some related links:

    Save and reset the viewport position relative to its topmost element

    I'm thinking of the following approach, but do not know how to implement it:

    First, an element (or text) within the viewport must be identified as a locator reference. Then the distance from that to the top of the viewport is measured. After the toggle has been activated, the location of the viewport top can be reset to that distance from that element.

    See: https://developer.mozilla.org/en-US/docs/Web/API/Document/elementFromPoint and http://kirbysayshi.com/2013/08/19/maintaining-scroll-position-knockoutjs-list.html

    This is a rather cludgy way to do it. See the next section instead. 23:40, 3 June 2017 (UTC)

    Identify the elements in the viewport

    I would like to find the topmost element that starts within the viewport.

    Check a particular element to determine if it is in the viewport
    • From refdesk (computer):

    You can get the position of an element, relative to the viewport, with code from http://stackoverflow.com/questions/442404/retrieve-the-position-x-y-of-an-html-element. You can then keep that element on the screen with code from http://kirbysayshi.com/2013/08/19/maintaining-scroll-position-knockoutjs-list.html. The two websearches I used to find these were https://duckduckgo.com/?q=js+get+top-left+object and https://duckduckgo.com/?q=js+scroll+element+to+viewport+position. (quote from LongHairedFop (talk) 13:53, 11 December 2016 (UTC))

    How to get (and process) all elements on the page

    This approach can be used to create a function to check every element's position against the viewport's position, to determine which element is the topmost in the viewport. One problem is that some elements might be inside other elements, such as navigation sidebars, but most of those will be over on the right of the page, so you can check the x-coordinate to filter those out.)

    How to get position of an element

    Find and adjust viewport position

    Find viewport position

    The goal here is to maintain the position of the scroll, with respect to the topmost list entry on the screen, and have the formatting change while maintaining that position.

    Some potentially relevant resources:

    Get offsets of viewport
    difference between heights
    scrollTop
    Find center of viewport

    Set viewport position

    A possible solution

    The functionality I'm trying to add to this script is to reposition the viewport to restore it to where it was in the text after some text has been hidden or unhidden.

    I've been searching for any and all pages that can explain any part of the problem, and have listed the ones I've found so far above.

    Talk-through 1

    Maybe this approach would work:

    1. We can get the y-offset for the top of the viewport with window.pageYOffset
    2. We can get the y-offset for the bottom of the viewport with window.pageYOffset + window.innerHeight
    3. this explains how to get the position of a particular element
    4. We can gather all elements on a page to a list using http://stackoverflow.com/questions/4256339/javascript-how-to-loop-through-all-dom-elements-on-a-page
    5. Then we can loop through all those elements comparing their position with that of the viewport
    6. Once that is done, we should know the topmost element inside the viewport. Record that into a variable.
    7. Then that variable is used to get a y-offset after annotations have been hidden/reshown.
    8. Use that offset to reposition the viewport using scrollTop
    Talk-through 2

    Put another way:

    1. Determine and store the identity of the element inside the viewport that is closest to the top of the viewport; that is the "targetElement". To do this, do the following:
      1. Declare variable targetElement
      2. Determine the position of the top of the viewport; viewportOffset
      3. Declare the variable offsetDifference (the distance between targetElement and the top of the viewport), and set it to an initial value of 10,000
      4. Make list of all elements on page: someElement
      5. Do a for loop on the someElement list
        1. Determine element's position
        2. If the element is within the viewport
          1. And if that element is closer to the top than the last element
            1. Set targetElement = that element
    2. After annotations are hidden or shown...
    3. Set the viewport position relative to the targetElement, by offsetDifference

    Adjust viewport position by difference between height of anno elements above viewport before and after the hide or show

    From Wikipedia talk:WikiProject JavaScript#I'm stumped: How do you save a location in the viewport to reposition the viewport later?:

    I think I've got an approach that could work – for elements above the veiwport, get the difference in height from before hiding annotations to after hiding annotations, then scroll the window up by that amount.

    In code, this would be something like the following

    //Select the set of annotations that are above where the viewpoint is scrolled to
    var $annos_above = $(".anno").filter( function(){
        var rect = this.getBoundingClientRect();
        if ( rect.bottom < 0 ) {
            return true;
        } else {
            return false;
        }
    } );
    
    //For each annotation above the viewport, get the difference in height in the containing element as that annotation is hidden
    var scroll_amount = 0;
    $annos_above.each( function(){
        var height_before = $(this).parent().outerHeight(true);
        $(this).hide();
        var height_after = $(this).parent().outerHeight(true);
        scroll_amount = scroll_amount + (height_after-height_before);
    } );
    
    //Hide the remaining annotations
    $( ".anno" ).hide();
    
    //Scroll the window by the required amount
    window.scrollBy(0, scroll_amount);
    

    - Evad37  05:06, 28 May 2017 (UTC)

    This looks way more efficient than the approach I've been working on above. Thank you. I'll see what I can do with it. The Transhumanist 23:38, 3 June 2017 (UTC)

    Complication

    @Evad37: I inserted the code that you provided (above) into the script, and the script repositioned the viewport in a surprising way.

    It realigned to the script's menu item on the sidebar. I hadn't noticed before that it has been doing this all along. Apparently it does this because of following code near the end of the function:

        // now we have to update the menu item 
        // (referred to in this script as "annoSwitch"). 
        // To do that, first we remove it (if it exists):  
        if ( annoSwitch ) {
            annoSwitch.parentNode.removeChild(annoSwitch);
        }
    
        // and then we create it (or its replacement) from scratch:
        annoSwitch = mw.util.addPortletLink( 'p-tb', '#', 'Annotations \(show\)', 'ca-anno', 'Show the annotations', 'a' );
    

    Maybe this problem could be fixed with the Window scrollTo() Method, if there was some way to record the scroll position of the window in the first place. If there was, the measurement could be taken before the menu item was updated, and then the position restored via window.scrollTo(xpos, ypos) after the change was completed.

    I tried sandwiching the menu item updating operations with y = window.scrollY; and window.scrollTo(0, y);, but it is not working for some reason. I placed var y; at the beginning of the script.

    I was very impressed with the solution you dreamed up above, and was wondering if you might have any ideas on how to fix this complication.

    I look forward to your reply, The Transhumanist 16:01, 8 July 2017 (UTC)

    I'm not sure if this is the problem, but you probably shouldn't be creating and removing portlet links each time the subroutines run – just define it once, at the start. Something like
                    // get the value of our status variable from memory
                    // (this tells us what mode to start in)
                    var annostatus = localStorage.getItem('annostatus');
    
                    // run the function corresponding to the current status
                    if ( annostatus === "hide" ) {
                        //Create portlet link in (show) state
                        mw.util.addPortletLink( 'p-tb', '#', 'Annotations \(show\)', 'ca-anno', 'Show the annotations', 'a' );
                        //then do the hiding
                        annoHide();
                    } else {
                        //Create portlet link in (hide) state
                        mw.util.addPortletLink( 'p-tb', '#', 'Annotations \(hide\)', 'ca-anno', 'Hide the annotations', 'a' );
                        //then do the showing
                        annoShow();
                    }
    
                    $('#ca-anno').click( function ( e ) {
                        e.preventDefault();
                        var $portletLink = $('#ca-anno').find('a');
                        var portletTitle = $portletLink.attr('title');
                        var portletText = $portletLink.text();
                        if ( portletText.includes('hide') ) {
                            //toggle portlet title/text
                            $portletLink.attr('title', portletTitle.replace('Hide', 'Show')).text(portletText.replace('hide', 'show');
                            //then do the hiding
                            annoHide();
                        } else {
                            //toggle portlet title/text
                            $portletLink.attr('title', portletTitle.replace('Show', 'Hide')).text(portletText.replace('show', 'hide');
                            //then do the showing
                            annoShow();
                    } );
                } );
    

    And remove the portlet creation/removal code from within annoHide and annoShow. - Evad37  02:32, 9 July 2017 (UTC)

    Find/verify non-li list-lead entries

    Fix annotation delimiters (to ndashes)

    See User:GregU/dashes.js.

    Discussions

    Post new discussion threads below.

    The Bug Report

    Hi, @The Transhumanist:. I've discovered an unintended side-effect caused by a line of code in your script, or should I say the line of code.

    cont.outerHTML = cont.outerHTML.replace(/(<li>.*?)( –.*)/g,'$1<span class="anno">$2</span>');
    

    This code strips action handlers from DOM elements which are descendants of mw-content-text. This notably affects 'buttons', such as the 'show/hide' button in the following templates:

    Extended content

    Peekaboo.

    You might be able to prevent this by iterating through <li> elements, like so:

    $("#mw-content-text li").each(function()
    {
        $(this).html($(this).html().replace(/(.*?)( –.*)/g,'$1<span class="anno">$2</span>'));
    });
    

    Let me know if this helps! Regards, GUYWAN ( t · c ) 12:20, 6 June 2019 (UTC)

    1. ^