Toggle menu
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

MediaWiki:Common.js: Difference between revisions

MediaWiki interface page
No edit summary
SEO: backfill meta description + image alt attributes
 
(24 intermediate revisions by 2 users not shown)
Line 1: Line 1:
/* Any JavaScript here will be loaded for all users on every page load. */
/* Site JS — loaded on every page (MediaWiki:Common.js). */


$(document).ready(function() {
/* SEO fixes (Lighthouse "meta description" + "image alt"). Citizen renders
    // True accordion behavior: collapse others when one is expanded
  og:description but not <meta name="description">, and MediaWiki renders inline
    $('.accordion-section').on('click', function(e) {
  images with no alt attribute, so we backfill both client-side. */
        var $this = $(this);
( function () {
        // If clicking the header (not a link inside content), toggle it
// 1. Mirror og:description into a real meta description if missing.
        if (e.target.tagName !== 'A' && !$this.hasClass('mw-collapsed')) {
if ( !document.querySelector( 'meta[name="description"]' ) ) {
            $this.addClass('mw-collapsed');
var og = document.querySelector( 'meta[property="og:description"]' );
        } else if (e.target.tagName !== 'A') {
if ( og && og.content ) {
            $('.accordion-section').not(this).addClass('mw-collapsed'); // Collapse all others
var m = document.createElement( 'meta' );
            $this.removeClass('mw-collapsed'); // Expand this one
m.setAttribute( 'name', 'description' );
        }
m.setAttribute( 'content', og.content );
    });
document.head.appendChild( m );
}
}


    // Disable link clicks in collapsed sections
// 2. Give every image an alt attribute if it lacks one, derived from the
    $('.accordion-section.mw-collapsed a').on('click', function(e) {
//    wrapping link's title (page/script name) or the file name.
        e.preventDefault(); // Prevent link from working when collapsed
document.querySelectorAll( 'img:not([alt])' ).forEach( function ( img ) {
    });
var link = img.closest( 'a' );
 
var alt = ( link && link.getAttribute( 'title' ) ) || '';
    // Re-enable links when expanded
if ( !alt ) {
    $('.accordion-section').on('click', function() {
var src = img.getAttribute( 'src' ) || '';
        if (!$(this).hasClass('mw-collapsed')) {
alt = decodeURIComponent( src.split( '/' ).pop() || '' )
            $(this).find('a').off('click'); // Remove the preventDefault when expanded
.replace( /^\d+px-/, '' )
        }
.replace( /\.[a-z0-9]+$/i, '' )
    });
.replace( /[_-]+/g, ' ' )
});
.trim();
}
img.setAttribute( 'alt', alt );
} );
}() );