I am trying to customize a plugin that renders the images of a Tumblr post with the following function.
So far I've only managed to add the class .photoset to the ul of a photo post, if there are 2 or more images.
function getImages(post) {
// console.log(post)
var html = [];
html.push("<ul class='tumblr_post_images'>")
$.each(post.photos, function (i, photo) {
html.push('<li class="photo"><img src=' + photo.alt_sizes[0].url + '></li>')
})
$('.post_photo ul').has('li:nth-child(n+2)').addClass("photoset");
html.push("</ul>")
return html.join("");
};
Ideally I would like it to render an ul only if there are more than 2 images in a post so that the markup is clean. I have tried some conditional statements but I just can't get this to work. Any help will be much appreciated.
UPDATE Thanks to T.J. Crowders' answer I managed to find the solution to my problem. Here's the code that works:
//Function to retrieve all the images from the post. This builds an array which is then returned as html list of images.
function getImages(post) {
var html = [];
// Get the HTML
if (post.photos.length === 1) {
$.each(post.photos, function (i, photo) {
html.push('<img src=' + photo.alt_sizes[0].url + '>')
})}
else {
// More than one
html.push("<ul class='photoset'>")
$.each(post.photos, function (i, photo) {
html.push('<li class="photo"><img src=' + photo.alt_sizes[0].url + '></li>')
});
html.push("</ul>");
}
return html.join("");
}
UPDATE 2 There was a bug in T.J. Crowders' original answer. He fixed it and now his answer works! Thanks!
basically I want to create an ul only if there are 2 or more images in a photo post
Then simply check post.photos.length
:
function getImages(post) {
var html = [];
// Get the HTML
if (post.photos.length) {
// We have at least one image
if (post.photos.length === 1) {
// Just one image
html.push('<img src=' + post.photos[0].alt_sizes[0].url + '>');
}
else {
// More than one
html.push("<ul class='tumblr_post_images'>")
$.each(post.photos, function (i, photo) {
html.push('<li class="photo"><img src=' + photo.alt_sizes[0].url + '></li>')
});
html.push("</ul>");
}
}
// Add or remove the class depending on whether we have more than one
$('.post_photo ul').toggleClass("photoset", post.photos.length > 1);
// Return the HTML (why are we returning it rather than putting it in the element here?)
return html.join("");
}
Also note I've added in the missing semicolons (strongly recommend not relying on the horror that is Automatic Semicolon Insertion) and removed the unnecessary one (function declarations are declarations, not expressions; there is no ;
at the end of them).