About three years ago I bought a domain name, intending, as always, to launch a project with it. Here we are three years later and I've done exactly no work on the project ¯_(ツ)_/¯
To practice some JavaScript, I decided to explore Unsplash's API to create an interactive placeholder in the meantime.
Breaking it down
const numItemsToGenerate = 1;
This just sets us up for the number of items we’ll request from the service.
function renderItem(){
fetch(`https://source.unsplash.com/1600x900/?beach`).then((response) => {
let item = document.createElement('div');
item.classList.add('item');
item.innerHTML = `<img class="beach-image" src="${response.url}" alt="beach image"/>`
document.body.appendChild(item);
})
}
This actually pulls the photo in and passes it to the div it created (item). In the URL https://source.unsplash.com/1600x900/?beach you could remove the slug or input another search term instead. Use their documentation to further customize, including images from specific users, particular sizes of image, or lots of other parameters.
Because I just wanted to set the image as the full background, I’m appending the img to innerHTML, rather than targeting a particular div or section on the page.
If you wanted to target a specific ID or class, you’d add something like this to the script:
let item = document.getElementByID('existing');
item.existing = `<img class="beach-image" src="${response.url}" alt="beach image"/>`
Then to pass through and render the image:
for(let i=0;i<numItemsToGenerate;i++){
renderItem();
}
In retrospect
At first, it was wild to think about using JS only and not building in any HTML to display the image, so first I tried building a div into the HTML body. I tried using class names and setting IDs, and I couldn't seem to target it, so I flipped to this different strategy using a tutorial as a guide.
Once I got the API working and displaying, the image dimensions were wild - turns out I was including the image dimensions in the source URL, so I pulled that out and created a CSS class for img since there was only going to be one displaying.
I made this just as a way to practice JavaScript and generate random images that would make me happy to look at. It's also the first time I've explored an API or read up on documentation for a purpose other than proofing/editing/writing.
In revisiting it now, I'm seeing another way I could have set the image as the body-background rather than creating a div and using a CSS class to size the photo which is kind of exciting - I'm ~ learning ~!






Nice! I just used Lorem Picsum for a quick mess around pen I did but I like the idea of using Unsplash API for learning, going to have to give it a try.