To create a photo fetch app in JavaScript using the Fetch API to interact with the Unsplash API, follow these steps:
Step 1: Sign up and obtain an API access key from Unsplash.
Visit the Unsplash Developer website (https://unsplash.com/developers) and sign up for an account. Create a new application and obtain an API access key.
Step 2: Create an HTML file.
Create a new HTML file and add the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<!DOCTYPE html> <html> <head> <title>Unsplash Photo Fetch App</title> </head> <body> <h1>Unsplash Photo Fetch App</h1> <button id="fetch-btn">Fetch Photo</button> <div id="image-container"></div> <script src="app.js"></script> </body> </html> |
Step 3: Create a JavaScript file.
Create a new JavaScript file named app.js
in the same directory as your HTML file and add the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
const accessKey = 'YOUR_UNSPLASH_ACCESS_KEY'; const fetchBtn = document.getElementById('fetch-btn'); const imageContainer = document.getElementById('image-container'); fetchBtn.addEventListener('click', fetchPhoto); function fetchPhoto() { const apiUrl = `https://api.unsplash.com/photos/random/?client_id=${accessKey}`; fetch(apiUrl) .then(response => response.json()) .then(data => { const imageUrl = data.urls.regular; const altText = data.alt_description; const image = document.createElement('img'); image.src = imageUrl; image.alt = altText; imageContainer.innerHTML = ''; imageContainer.appendChild(image); }) .catch(error => { console.error('Error:', error); }); } |
In the JavaScript code above, replace 'YOUR_UNSPLASH_ACCESS_KEY'
with the access key you obtained from Unsplash.
The code retrieves the HTML elements using getElementById
, adds a click event listener to the “Fetch Photo” button, and defines a function fetchPhoto
to handle the photo fetching process.
Inside fetchPhoto
, it constructs the API URL using the access key and makes a fetch request to the Unsplash API. The response is then parsed as JSON using response.json()
. The photo URL and alt text are extracted from the response data, and a new img
element is created and appended to the imageContainer
element