Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simpler random Unsplash images #39

Open
oliverjam opened this issue Apr 30, 2021 · 0 comments
Open

Simpler random Unsplash images #39

oliverjam opened this issue Apr 30, 2021 · 0 comments

Comments

@oliverjam
Copy link

window.addEventListener("load", () => {
let randomNum = Math.floor(Math.random() * 10);
fetch("https://api.unsplash.com/photos/random?query=skatepark&client_id=${process.env.API_KEY}&orientation=portrait")
.then((response) => {
if (!response.ok) throw new Error(response.status);
return response.json()
})
.then((data) => {
document.querySelector('.bg-image').src = data.urls.regular;
})
.catch((error) => console.log(error));
});

This code is cool, and it's great to practice client-side stuff like fetching (since we're spending so much time on the server).

However there is a much simpler way to achieve this: https://source.unsplash.com/

You can construct a URL like https://source.unsplash.com/random/1000/800 to get a random picture of those dimensions. It even supports search terms by adding search params like ?skateboard,banana to the end.

This would allow you to simply use that URL as a CSS background-image for the page:

html {
  background-image: url('https://source.unsplash.com/random/1000/800');
  background-size: cover;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant