User:MJL/wordsCounter.js

// Originally found at User:GoldenRing/wordcount.js // This function shamelessly copied from https://stackoverflow.com/a/11348383/274460

mw.loader.load('//en.wikipedia.org/w/index.php?title=User:MJL/wordsCounter.css&action=raw&ctype=text/css', 'text/css'); // Import stylesheet

var namespace = mw.config.get( 'wgCanonicalNamespace' ); var node = mw.util.addPortletLink(   'p-tb',    '#',    'Word count',    'pt-wordcount',    'Add word counts to each section',	null,    '#t-info'  ); function countWords(h) { $(h).each(function(i, match) { var elements = $(match).nextUntil(h);  elements.find(':hidden').addClass('wordcount-ignore');  elements.find('*').filter(function { return $(this).css('text-decoration').match(/line-through/); }).addClass('wordcount-ignore');  elements.find('div#siteSub').addClass('wordcount-ignore');  elements.find('div#contentSub').addClass('wordcount-ignore');  elements.find('.reflist-talk').addClass('wordcount-ignore');  elements.find('div#jump-to-nav').addClass('wordcount-ignore');  elements = elements.not('.wordcount-ignore');  var text = elements.ignore('span.localcomments').ignore('.wordcount-ignore').text;  var search = /(\d{1,2}):(\d{2}), (\d{1,2}) ([A-Z][a-z]+) (\d{4}) \(UTC\)/g;  text = text.replace(search, '');  text = text.split(/\s/).filter(function(d) { return d.length > 0; })                                        .filter(function(d) { return d.match(/[a-zA-Z0-9]/); }); var count = text.length; $(match).append($(' ' + count.toLocaleString + ' words ')); }); } if ( namespace === 'Wikipedia' || namespace === 'Wikipedia_talk' ) { $.when( mw.loader.using( ['mediawiki.util'] ), $.ready ).done( function { node; }); }

$(node).on( 'click', function {	countWords('h1');	countWords('h2');	countWords('h3');	countWords('h4'); } );