· 6 years ago · Nov 10, 2019, 10:56 AM
1function search() {
2 let yourAPI_KEY = "54a657a524bbaa7643aadcbdcc0c0b68"; //Personal key to get access to flickr
3 let userKeyword = document.getElementById("userKeyword").value; //Input of user to search for photos
4 let flickrURL = `https://api.flickr.com/services/rest?method=flickr.photos.search&api_key=${yourAPI_KEY}&text=${userKeyword}&per_page=20&format=json&nojsoncallback=1`; //URL to access the flickr with Json as return value
5
6
7 //Make API request
8 fetch(flickrURL)
9 .then(response => {
10 return response.json(); //Get the url to return response as json format
11 })
12 .then(data => {
13 console.log(data);
14 // Access the properties of the object returned by response
15
16 data.photos.photo.forEach(getPic => {
17 var farmId = getPic.farm;
18 var serverId = getPic.server;
19 var id = getPic.id;
20 var secret = getPic.secret;
21
22 //let result = `<img src ="https://farm${farmId}.staticflickr.com/${serverId}/${id}_${secret}.jpg">`;
23 let result = `https://farm${farmId}.staticflickr.com/${serverId}/${id}_${secret}.jpg`;
24 // According to flickr URL format //https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg* to retrieve the photos using keywords
25
26 //Parent element
27 let output = document.getElementById("output");
28
29 //New img item
30 let flickrImage = document.createElement("img");
31 flickrImage.src = result;
32
33 flickrImage.addEventListener("click", () => {
34 // Cleaning the lightbox
35 lightbox.querySelectorAll('*').forEach(n => n.remove());
36 //Another method: lightbox.innerHTML = "";
37
38 lightbox.classList.add("active");
39 const img = document.createElement("img");
40 img.src = flickrImage.src;
41 lightbox.appendChild(img);
42 });
43
44 output.appendChild(flickrImage);
45 });
46 })
47 .catch(error => {
48 console.log(error);
49 });
50}
51
52// create lightbox div using js
53const lightbox = document.createElement("div");
54lightbox.style.borderWidth = "thick";
55lightbox.style.borderColor = "black";
56lightbox.style.borderStyle = "solid";
57lightbox.id = "lightbox";
58
59// Inserting the lightbox BEFORE user input field.
60let searchBox = document.getElementById("userKeyword");
61document.body.insertBefore(lightbox, searchBox);