User:Simon04/gallerySize.js

Note: After saving, you have to bypass your browser's cache to see the changes. Internet Explorer: press Ctrl-F5, Mozilla: hold down Shift while clicking Reload (or press Ctrl-Shift-R), Opera/Konqueror: press F5, Safari: hold down Shift + Alt while clicking Reload, Chrome: hold down Shift while clicking Reload.
// based on https://commons.wikimedia.org/wiki/User:JuTa/gallerySize.js
jQuery(document).ready(function() {
  if (typeof gallerySize === 'undefined') {
    gallerySize = 180;
  }
  var pattern = /^(.*\/)([1-9]+[0-9]*)(px[^\/]+)$/;
  var galleries = document.getElementsByClassName('gallerybox');
  for (var i = 0; i < galleries.length; ++i) {
    var images = galleries[i].getElementsByTagName('img');
    for (var j = 0; j < images.length; ++j) {
      var img = images[j];
      var src = img.getAttribute('src');
      var e = pattern.exec(src);
      if (e) {
        var p = img.parentNode;
        var imgN = document.createElement('img');
        imgN.setAttribute('src', e[1] + Math.round((gallerySize * Number(e[2])) / 120) + e[3]);

        imgN.onerror = (function(imgN, img) {
          return function() {
            imgN.onerror = '';
            imgN.parentNode.replaceChild(img, imgN);
            return false;
          };
        })(imgN, img);

        for (; !p.classList.contains('gallerybox'); p = p.parentNode) {
          p.style.width = 'unset';
        }
        p.style.width = gallerySize + 5 + 'px';

        img.parentNode.replaceChild(imgN, img);
      }
    }
  }
});