Post by zagibu on Sept 14, 2021 6:40:17 GMT -8
Hey guys, I've written a small plugin that allows you to click images in a message and opens them in a popup. But it stops working when you go to page 2 of the messages in a thread, or really after any such page change. I suspect it has something to do with variable scope and my script scoped variables being lost somehow, or the onload function not running when there is a page change.
Here's the code:
var modal = $('\
<div id="n23-sis-showcase" class="n23-sis-showcase">\
<button id="n23-sis-close" class="n23-sis-close" type="button">X</button>\
<img id="n23-sis-image" class="n23-sis-image" src="">\
</div>\
');
var images = [];
var total = 0;
var current = 0;
var height = 0;
var width = 0;
var tempImage = new Image();
$(document).ready(function() {
modal.appendTo("body");
$("div.message").find("img").click(showPopup);
$("#n23-sis-showcase").click(closeModal);
$("#n23-sis-close").click(closeModal);
$("#n23-sis-image").click(function(event) {
event.stopPropagation();
nextImage()
});
tempImage.onload = loadImage;
$("#n23-sis-showcase").hide();
});
$(document).keyup(function(e) {
if (e.key === "Escape") {
closeModal();
}
});
function showPopup() {
var clicked = this;
images = $(clicked).parents("div.message").find("img");
total = images.length;
current = 0;
images.each(function(i) {
if (clicked.src === this.src) {
current = i;
}
});
nextImage(false);
$("#n23-sis-showcase").show();
}
function closeModal(event) {
$("#n23-sis-showcase").hide();
}
function nextImage(cycle = true) {
if (cycle) {
current = (current + 1) % total;
}
tempImage.src = images[current].src;
}
function loadImage() {
width = tempImage.width;
height = tempImage.height;
var ratio = width / height;
var frameWidth = $("#n23-sis-showcase").width();
var frameHeight = $("#n23-sis-showcase").height();
var frameRatio = frameWidth / frameHeight;
if (width > frameWidth || height > frameHeight) {
if (ratio > frameRatio) {
$("#n23-sis-image").attr("width", frameWidth);
$("#n23-sis-image").attr("height", frameWidth / ratio);
} else {
$("#n23-sis-image").attr("width", frameHeight * ratio);
$("#n23-sis-image").attr("height", frameHeight);
}
} else {
$("#n23-sis-image").attr("width", width);
$("#n23-sis-image").attr("height", height);
}
$("#n23-sis-image").attr("src", images[current].src);
tempImage = new Image();
tempImage.onload = loadImage;
}
Here's the CSS:
.n23-sis-showcase {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: black;
z-index: 9997;
text-align: center;
vertical-align: middle;
}
.n23-sis-close {
position: fixed;
top: 0;
right: 0;
z-index: 9999;
}
.n23-sis-image {
z-index: 9998;
}