samedi 1 juin 2019

Loop through all image captions and change text alignment to either left or center?

I have created an image gallery using the code from the W3Schools's modal lightbox. I made some changes to it to make it fit to my needs, eg. I have the images listed in separate php files (photography.php, 3dmodels.php etc) and then included into the gallery php file. Also the caption text is not taken from the alt but from a div. The image gallery works fine (in Chrome anyway).

When an image is open in the big view the caption is centered, and that looks ugly when there is more than one row of text. Having the text aligned to left isn't good either because some vertical images are narrow. So, how to make the captions align to the left when there is more than one row of text and align to the center when there is only one row?

The gallery has 5 categories (#gall_valittu) and a total of 103 images with captions (#caption_text). I have tried with one "for loop" and now with two loops. The actual-jquery plugin (.actual(outerHeight)) is for getting the height of the whole text. I had problems with that one too but this option seems to help.

$(document).ready(function() {
    var caption_div = $("div#gall_valittu"); // Gives 5 divs
    for (var z = 0; z < caption_div.length; z++) {
        var tekstit = $("p#caption_text"); // Gives 103 images
        for (var y = 0; y < tekstit.length; y++) {
            var caption_area = $("#caption");
            //var caption_txt = $("p#caption_text");
            var area = caption_area.outerHeight();
            var txt = $("p#caption_text").actual("outerHeight"); //jquery.actual.min.js !!!
                if (txt < area) {document.getElementById("caption_text").style.textAlign = "center";}
                else {document.getElementById("caption_text").style.textAlign = "left";}
        }   
    }
});

My problem is I can't get the "for loop" working. It stops after the first image. It aligns the text correct, though. I have tried without the if-statement to see if the for loop works and it doesn't. I don't really know javascript, my skill is mostly copy/paste style.

Aucun commentaire:

Enregistrer un commentaire