I have a sort-of working script to open all images in a specific div (called "note-viewer") in a new window. The div can't be edited by me to simply place regular anchors around the images or add an onclick function, and the images are too small in the div to view properly.
The problem is that it works perfectly the first time you click an image. If you click another image after that, you have to click it twice to make it work. Once you try for a third image, nothing happens. It doesn't throw any kind of error. You click and it just sits there.
I need it to be one click on any and every image to open it in a new window.
Here's the code:
$("#note-viewer img").click(function () {
var imageLink = $(this).attr("src");
$("#note-viewer img").each(function () {
var myWindow = window.open("", "Image", "_blank", "toolbar=no,scrollbars=no,resizable=yes");
myWindow.document.write("<head><title>Image</title></head>");
myWindow.document.write("<img src=" + imageLink + ">");
return myWindow;
});
});
I know; I'm using document.write when I shouldn't. "Bad, Dev. Bad!" But it's only for use internally in our department.
UPDATE
I just tried simplifying it by trying to use jQuery to wrap the image tags with anchor tags as below:
$(function () {
$('#note-viewer img').wrap(function () {
return '<a href="' + $(this).attr('src') + '"></a>';
});
});
That didn't work at all.
Here's the best working solution I've come up with which is a modification of something posted by @Jazmit with a bit of jQuery thrown in:
https://stackoverflow.com/a/62285566/11420625
After the first image is clicked, the rest still require two clicks for some reason, but they all work. Also, it eliminates the
document.write
.QUICK ADDITION: Turns out that it requires two clicks because the Trix Editor is focusing me (the user) on the image to add a caption on the first click. I have no idea why it doesn't behave that way on the very first image you click.