Spoiler alert for img

Code

by Denis Minov

HTML

<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQiwgrJeAJN-7lcy92N51uP7XzccK_p-fTSJNCXPLPSVih8wqPf" spoiler>

CSS

img[spoiler=""], img[spoiler="true"] {opacity: 0;}
.thisSpoiler {position: relative; overflow: hidden;}
.thisSpoiler > img {display: block; opacity: 1; z-index: 1; border: 0;}
.thisSpoiler::before, .thisSpoiler::after {position: absolute; left: 0; right: 0; transition: opacity .3s linear; pointer-events: none;}
.thisSpoiler::before {content: ''; display: block; width: 100%; height: 100%; background: #000; z-index: 2; top: 0; bottom: 0;}
.thisSpoiler::after {content: 'Это изображение содержит в себе спойлер!\0aНаведите, чтобы посмотреть.'; display: inline-block; max-width: 100%; max-height: 100%; text-align: center; font-size: 12px; color: #fff; white-space: pre-line; z-index: 3; left: 50%; top: 50%; transform: translate(-50%, -50%);}
.thisSpoiler:hover::before, .thisSpoiler:hover::after, .thisSpoiler:active::before, .thisSpoiler:active::after {opacity: 0;}

JavaScript

// конверт bb-кода из текста определённого тега (в моём случае div с классом .message), нужный img с атрибутом для работы спойлера.
// Важно, если будете применять данный код, то используйте его выше, чем код ниже. Лучше в <head>
function SpoilerAlerBB(elem) {
  let reg = /\[img-spoiler\]((?:http|https):\/\/\S+(?:jpg|jpeg|png|gif))\[\/img-spoiler\]/gi;
  if(elem.length>0) {
    elem.each(function(){
      let html = $(this).html();
      if(html.match(reg)) $(this).html(html.replace(reg, '<img src=\"$1\" spoiler>'));
      reg = reg;
    });
  }
}
SpoilerAlerBB($('.message'));

// Сам код скрипта. Лучше расположить его в конце тега <body>
$(window).on('load', function(){
  $('img[spoiler=""], img[spoiler="true"]').each(function(){
    let style = 'display: '+($(this).css('display') == 'inline' ? 'inline-block' : $(this).css('display'))+';\
      width: '+$(this).css('width')+';\
      height: '+$(this).css('height')+';';
    $(this).wrap('<div class=\"thisSpoiler\" style=\"'+style+'\">');
  });
});