Short summary: I'm in a Jekyll situation where I need to find the src url for each individual image and post it back into an a href="imgurl". jQuery or Javascript.
What I tried so far:
$(document).ready(function(){
var postTitle = document.title.replace(/ /g,'');
$("article img").each(function() {
imgsrc = this.src;
console.log(imgsrc);
});
$("article img").wrap('<a href="' + imgsrc + '" data-lightbox="' + postTitle + '"></a>');
The reason I'm wrapping the article img in an a-tag, is because prose.io, which I use for the markdown, automatically assigns the images within p-tags.
What I want to do eventually is to group all the images in the same post (data-lightbox)and create a lightbox gallery automatically from the added images to the page.
With my existing code, I've managed to get the url from the first added image, but unfortunately, all the images in the post get assigned the same url as the first. They show on-site as the proper images, but the url is just the same as the first image (position [0] in the array). When I click an image, the lightbox opens and the correct amount of images appear, but they are all showing the first image. The console.log prints correctly all the urls of the images in the post.
EDIT-BONUS: Validated! As a bonus-question: If I were to do the same thing with the alt text, copying it into the data-title attribute, how would I proceed? Currently have this:
var altText = $("img", this).attr("alt");
$("article img").each(function() {
$(this).wrap('<a href="' + this.src + '" data-lightbox="' + postTitle + '" data-title="' + altText + '"></a>');
});
Again, it just gets me the first image alt, and assignes it to all the images.
I hope some of you know how to get around this mess.
In advance, thanks for your time!
You're overriding imgsrc
each time there is an image.
Try something like this :
$("article img").each(function() {
var src = this.src;
var alt = $(this).attr("alt");
$(this).wrap('<a href="' + src + '" data-lightbox="' + postTitle + '" data-title="' + alt + '"></a>');
});
Check .attr()
for more informations !