07-Images

In this module, we'll add the code for pulling off thumbnails from the JSON data.

The Code

Be meticulous as you do this next one. We've added steps for additional code. Be sure that you are paying attention to where things go. Then, we'll break the code down at the end:

 function displayResults(json) {
     //CODE OMITTED
  } else {
  for(let i = 0; i < articles.length; i++) {
      let article = document.createElement('article');
      let heading = document.createElement('h2');
      let link = document.createElement('a');
      let img = document.createElement('img');  //1
      let para = document.createElement('p');  
      let clearfix = document.createElement('div');


      for(let j = 0; j < current.keywords.length; j++) {
        let span = document.createElement('span');   
        span.textContent += current.keywords[j].value + ' ';   
        para.appendChild(span);
      }

        //2
      if(current.multimedia.length > 0) {
        //3
        img.src = 'http://www.nytimes.com/' + current.multimedia[0].url;
        //4
        img.alt = current.headline.main;
      }

      clearfix.setAttribute('class','clearfix');

      article.appendChild(heading);
      heading.appendChild(link);
      article.appendChild(img); //5
      article.appendChild(para);
      article.appendChild(clearfix);
      section.appendChild(article);
    }
  }
};

Analysis

  1. We add an img variable that will create an image element.

  2. We use a conditional to check the JSON for data. There is a multimedia property in the JSON. You should go look for it in the json. If that has anything in it (if the length is greater than 0), then, we'll do some stuff in the next steps.

  3. If there is an object, we want to concatenate a string with the url for the html src value. We will add the first item in the multimedia array: current.multimedia[0].url. That is all confusing, so it helps here to think about a regular old image tag:

    <img src="www.myimage.com/54757578" alt="My Image" />

    We are building that for each result item.

  4. We need an alt if something should happen that the image isn't available. We set it to the value of the headline.

  5. We append the image to the article element for each of our items.

Run the App

You should see images when you run a search result:

Screenshot

Last updated