Skip to content

Instantly share code, notes, and snippets.

@scf37
Last active April 13, 2019 20:01
Show Gist options
  • Save scf37/b9eed984a705243c27527a2036f09c0f to your computer and use it in GitHub Desktop.
Save scf37/b9eed984a705243c27527a2036f09c0f to your computer and use it in GitHub Desktop.
const options = {
// background color
bgColor: 'rgba(0,0,0,0.9)',
// fade-in and fade-out duration
fadeDurationMs: 400,
// hide scroll when showing fullscreen image
hideScroll: true,
// fade overlay z index
zIndex: 999
};
/**
* Show given image on full screen
*
* @param self image url or img tag
*/
export function img_box(self) {
const container = initContainer();
const imgUrl = typeof self === 'string' ? self : self.src;
const bodyOverflow = document.body.style.overflow;
const image = new Image();
image.src = imgUrl;
image.style.maxWidth = '90%';
image.style.maxHeight = '90%';
image.style.margin = 'auto';
container.appendChild(image);
if (options.hideScroll) {
document.body.style.overflow = 'hidden'
}
container.style.display = 'flex';
window.setTimeout(() => container.style.opacity = 1, 0);
function onClick() {
container.removeEventListener('click', onClick);
container.style.opacity = 0;
window.setTimeout(function() {
container.style.display = 'none';
container.innerHTML = '';
document.body.style.overflow = bodyOverflow;
}, options.fadeDurationMs * 0.8);
}
container.addEventListener('click', onClick)
}
let imgboxContainer;
function initContainer() {
if (imgboxContainer) return imgboxContainer;
const o = document.createElement('div');
o.innerHTML =
'<div id="img_box" style="top:0px;left:0px;opacity:0;width:100%;height:100%;display:none;position:fixed;' +
'cursor:pointer;z-index:' + options.zIndex +';background-color:' + options.bgColor +
';transition:opacity ' + options.fadeDurationMs + 'ms"/>';
imgboxContainer = o.firstChild;
document.body.appendChild(imgboxContainer);
return imgboxContainer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment