How can the Flickr API be utilized with JavaScript functions?

In preparation for a project, we are required to utilize the Flickr API in order to display a collection of photos when a specific category is selected. I have successfully set up my categories on the left side of a flexbox container. However, I am struggling with configuring the system to display the Flickr API results tagged with 'tennis' when the user clicks on the tennis category.

Another issue I have encountered with the Flickr API is that the images lack titles underneath them, which is a necessary feature for my project. Additionally, no matter how much I attempt to adjust them, the images continue to appear in a single column. Any assistance or guidance on these matters would be greatly appreciated.

Being relatively new to coding, I would benefit from a clear explanation of how to resolve these challenges.

Below you will find the code snippet:

$("#tennis").click(function() {
  
  //api search for tennis
  let API_KEY = MY API KEY ";
  let tennisStr = "https://api.flickr.com/services/rest/?method=flickr.photos.search&tags=tennis&per_page=15&format=json&nojsoncallback=1&" + API_KEY;
  let photos = [];
  let nrequest;
  let nreceived;

  $(document).ready(function() {
    console.log(tennisStr);
    $.get(tennisStr, function(data) {
      fetchPhoto(data);
    });
  });

  function fetchPhoto(data) {
    nrequest = data.photos.photo.length;
    nreceived = 0;
    for (let i = 0; i < data.photos.photo.length; i++) {
      let photoObj = {
        id: data.photos.photo[i].id,
        title: data.photos.photo[0].title
      }
      photos.push(photoObj);
      getSizes(photoObj);
    }

    function getSizes(photoObj) {
      let getSizesStr = "https://api.flickr.com/services/rest/?method=flickr.photos.getSizes&format=json&nojsoncallback=1&" + API_KEY + "&photo_id=" + photoObj.id;
      $.get(getSizesStr, function(data) {
        nreceived++;
        photoObj.file = data.sizes.size[5].source;
        photoObj.full = data.sizes.size[data.sizes.size.length - 1].source;
        if (nreceived == nrequest) {
          display(photos);
        }
      });
    }

    function display(photos) {
      let htmlStr = "";
      for (let i = 0; i < photos.length; i++) {
        htmlStr += `<figure><a href=${photos[i].file}'><img src = "${photos[i].file}" height = "200" width = "200"></a><figcaption>photos</figcaption></figure>`;
      }
      $("#flickrphoto").html(htmlStr);
    }
  }
});
.flex-container {
  display: flex;
}

.flex-container>div {
  border: 1px solid black;
  flex-direction: column;
}

#navigation {
  flex-grow: 1;
  text-align: left;
}

#flickrphoto {
  display: flex;
  flex-grow: 2;
  text-align: center;
  flex-wrap: wrap;
  justify-content: center;
  flex-basis: auto;
}

#recenthistory {
  flex-grow: 1;
  text-align: left;
}

header {
  text-align: center;
  background-color: black;
  color: white;
  padding: 4rem;
}

.footer {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  background-color: black;
  color: white;
  text-align: center;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset=utf-8>
  <link rel="stylesheet" type="text/css" href="css/style.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script src="./js/main.js"></script>
  <title>Sports Album</title>
  <header>
    <h1>Sports Album</h1>
  </header>
</head>

<body>
  <div class="flex-container">
    <div id="navigation">
      <h2>Categories</h2><br>
      <div id="nav">
        <div id="tennis">
          <p>Tennis</p>
          </br>
        </div>
        <div id="football">
          <p>Football</p>
          </br>
        </div>
        <div id="swimming">
          <p>Swimming</p>
          </br>
        </div>
      </div>
    </div>
    <div id="flickrphoto">
      <h2>Flickr</h2>
    </div>
    <div id="recenthistory">
      <h2>Recent history</h2>
    </div>
  </div>

  <div class="footer">
    <p>Jasmine</p>
  </div>
</body>

</html>

Preview image of the current progress

Thank you for reviewing my work and providing guidance on addressing the issues I have encountered!

Answer №1

I have discovered some issues in your code:

HTML5:

  1. It is recommended to use only one version of jQuery. In this case, make sure to include the following script:
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  2. The <header> tag should be placed inside the <body> tag.
  3. You can utilize a class attribute instead of using an id for each div. Here's an example:

<div id="nav">
  <div id="tennis" class="request">
    <p>Tennis</p>
    <br />
  </div>
  <div id="football" class="request">
    <p>Football</p>
    <br />
  </div>
  <div id="swimming" class="request">
    <p>Swimming</p>
    <br />
  </div>
</div>

CSS:

  1. The images appear in a column despite editing efforts. Remove the line: flex-direction: column;.

To address this, try modifying your CSS as follows:

.flex-container > div {
   border: 1px solid black;
}

JavaScript/jQuery:

  1. Enclose your jQuery code within $(function(){});. For instance:

$(function()
{
   // Your code goes here...
});
  1. The variable API_KEY should be assigned a string value enclosed in double quotes. For example:
    let API_KEY = "39417c145483a7fb3ee91c5fe5bc93fe";
    .
  2. You can simplify making requests to the Flickr API by setting up a single function using
    $(".request").on("click", function() {
    . Consider utilizing .on("click").
  3. In your fetchPhoto function, replace data.photos.photo[0].title with data.photos.photo[i].title.
  4. Then, within your display function, ensure you print the correct titles by incorporating the following:

<figcaption>${photos[i].title}</figcaption>

Refer to this example below:

https://i.sstatic.net/vFEV0.jpg

Consider implementing something like this:

... (the remaining content has been omitted for brevity) ...

Have a fantastic day!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a button within a card: tips and tricks

As I work on designing web sites, I often face challenges. One of my go-to tools is bootstrap, especially when creating card elements. Here is the code I typically use for creating cards: <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/c ...

Dispatch keystrokes to a designated text field if they are not taken in by any other input

Is there a way to achieve the functionality seen in apps like Discord, where users can type into the message box even when it's not in focus? I am interested in implementing this feature only if no other input field on the page is currently focused. ...

Error message: Nextjs encounters hydration issue only in the production environment

I've been facing this issue for hours now. I deployed my Next.js application on Vercel and encountered numerous hydration errors there. Interestingly, in my local development environment, I don't experience any errors at all. I came across sugge ...

Obtaining a file using capybara independently of rails

Case Study: Attempting to access an external URL using Capybara for downloading a file. It is necessary to use Selenium or Webkit as the driver, since Rack-test does not allow visiting external URLs. This website utilizes iframes. The prompt for file dow ...

Using Vue.js: Execute a function with a delay, but start the delay over if there is any user input

Imagine a scenario where I have a form that is connected to an API and displays information based on user input. Whenever the user makes changes, such as adjusting the number of results per page, the component should react dynamically by loading new data. ...

Detecting mistakes on the server end

Fetching data in JSON format from my server to display as a table. $('#queryFrom').ajaxForm({ dataType: 'json', beforeSubmit: showRequest, / ...

Bootstrap navbar and its underlying area

I am struggling to effectively implement a navbar on my website. I currently have the following code snippet in the body section of my base.html file. (Should the navbar be placed in the head section instead?) <body> <div class="row" ...

Utilizing MutationObserver in JavaScript for Streamlined Code Execution

One of my functions utilizes a MutationObserver to track attribute changes in a specified element and logs them to the console. Below is an example where I pass 'card' elements in a foreach loop: track_attr_changes(element); The parameter ' ...

The rationale behind organizing analogous variables into groups

Currently, I am grappling with determining the optimal logic for grouping parameters within a specified tolerance level. Let me illustrate this with an example... Task1: parameter1=140 Task2: parameter1=137 Task3: parameter1=142 Task4: parameter1=139 Task ...

Having difficulty executing JavaScript code from the VB code behind

Recently, I have encountered a strange issue while working with ASP/VB.net. In my code behind VB file, I am trying to call a JavaScript function, but it seems like nothing is happening. Surprisingly, I have used a very similar method on several other pages ...

Ruling out the use of jQuery script within a dynamic framework

I have a unique jQuery script to create a "Back to Top" functionality: <script type="text/javascript"> $(document).ready(function(){ // Initially hide the #TopButton $("#TopButton").hide(); // Fade in the #TopButton on scrolling $(function () { ...

Cycle through every jQuery selector individually

Struggling with some calculations on my website application. Here's the situation: This is the structure of my HTML code: <table> <tr> <td><span class="sub_total">10</span></td> </tr> <tr& ...

Tips for creating a vertical scrollbar within a row component

Is there a way to create a scrollable parent v-row with a child v-row overflowing with content so that I can nest another v-row inside the v-col and ensure it remains within the scroll element? <v-row> <v-col> <v-row> <p ...

Achieving proper functionality of additional directives within uib-tab components

How can I utilize a callback function for uib-tab directives to refresh inner directives after tab rendering? I'm troubleshooting an issue with a third-party directive when used within the uib-tab directive from angular-bootstrap. The specific direct ...

How can I programmatically refresh a recursive ng-include in AngularJS?

Using a recursive script within my Angular application, I am displaying a visualization of multiple objects. However, whenever I modify the structure of an object dynamically, the view does not automatically update. It appears that the ng-include directiv ...

What is the best method for extracting specific JSON response elements and appending them to an array?

I've been utilizing the Nomics cryptocurrency API in my project. Below is an example of the Axios call: axios.get(apiURL + apiKey + apiSpecs) .then(function (response) { // sort data by highest market cap console.log(response.data) }) Here' ...

Unable to retrieve the field value from the Json Object

I have a JSON object that I need to parse and display in a data table, but I'm having trouble reading the contents of the object. Here is my JavaScript function: finalGrid: function(data){ console.log("Final Grid"); var strJson = JSON.strin ...

When an array is prototyped as a member of a JavaScript object, it becomes a shared property among all instances

Is anyone else surprised by this behavior? It really caught me off guard... I was expecting prototyped arrays to be private to each instance of a class rather than shared across all instances. Can someone confirm if this is the intended behavior and provi ...

Encountering a "Cannot modify" error in wp-admin while using inspect element

It seems like there is a slight error appearing in the Inspect Element Source Tab of Google Chrome (also checked in Firefox). I have searched extensively for a solution but haven't found anything helpful. My Wordpress theme displays wp-admin in inspec ...

Unable to invoke JS function in Drupal 5 file

In my current project using Drupal 5, I have a specific .js file that is included using the code: drupal_add_js(drupal_get_path('module','MTM')."/include/JS_form.js"); Additionally, there is an element on the page: <a onclick="MTM ...