mardi 19 mai 2020

Random Image Gallery with json?

I'm trying to make an infinity scroll of random images with a json file. I succeeded, the problem is, this should work without any server.
So I was trying to put all the information in a 'var' but now these images are not loading anymore.
Is there a way to fix it without needing a server?
Here is what I have so far:

HTML:


<body>
    <main>

    </main>

    <div class="container">
        <div class="text-center">
            <button onclick="setTimeout(getData,2000); return false" type="submit" id="button" value="Load more" class="button">
                    Load more</button>
        </div>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5/jquery.min.js"></script>
    <script src="main.js"></script>
    <script src="https://code.jquery.com/ui/jquery-ui-git.js"></script>
</body>


Everything, that is now written in var imgJson, was in images.txt.
Now, I've seen other people write it in a var, so I did that, but it doesn't work.
To be fair, I just learned about JSON, yesterday, so I'm pretty new to it.

JS:

// const URL = "images/images.txt"
var imgJson = {"items":[{
    "id": 1,
    "img": 'https:\/\/picsum.photos\/200\/300'
}, {
    "id": 2,
    "img": 'https:\/\/picsum.photos\/201\/301'
},
{
    "id": 3,
    "img": 'https:\/\/picsum.photos\/202\/302'
},
{
    "id": 4,
    "img": 'https:\/\/picsum.photos\/203\/303'
}
]}

getData();

function getData(){

    let main = document.querySelector("main");
    console.log("fetch some data");
    fetch(imgJson)
    .then(response => response.json())
    .then(data => {
        data.items.forEach(item => {
            let fig = document.createElement("figure");
            let img = document.createElement("img");    
            img.src = item.img;

            fig.appendChild(img);
            main.appendChild(fig);
        });
    });

}

$(document).ready(function(){
    $(".button").click(function(){
        $(this).addClass("active");

        setTimeout(function(){
            $(".button").removeClass("active");
        },2000);
    });
});


CSS (only the part with the image-part):


main {
        display: grid;
        grid-template-columns: 1fr 1fr 1fr 1fr;
        grid-gap: 1rem;
        width: 80vw;
        margin: auto;
        grid-template-rows: auto;
      }


main figcaption {
    font-size: 1rem;
    font-family: inherit;
}
main img {
    width: auto;
    height: auto;
    max-width: 100%;
}




Aucun commentaire:

Enregistrer un commentaire