freeCodeCamp Challenge Guide: Render Images from Data Sources

Render Images from Data Sources


Solutions

Solution 1 (Click to Show/Hide)
<script>
  document.addEventListener('DOMContentLoaded',function(){
    document.getElementById('getMessage').onclick=function(){
      req=new XMLHttpRequest();
      req.open("GET",'/json/cats.json',true);
      req.send();
      req.onload=function(){
        json=JSON.parse(req.responseText);
        var html = "";
        json.forEach(function(val) {
          html += "<div class = 'cat'>";
          // Add your code below this line
          html += "<img src = '" + val.imageLink + "' " + "alt='" + val.altText + "'>";
          
          // Add your code above this line
          html += "</div><br>";
        });
        document.getElementsByClassName('message')[0].innerHTML=html;
      };
     };
  });
</script>
<style>
  body {
    text-align: center;
    font-family: "Helvetica", sans-serif;
  }
  h1 {
    font-size: 2em;
    font-weight: bold;
  }
  .box {
    border-radius: 5px;
    background-color: #eee;
    padding: 20px 5px;
  }
  button {
    color: white;
    background-color: #4791d0;
    border-radius: 5px;
    border: 1px solid #4791d0;
    padding: 5px 10px 8px 10px;
  }
  button:hover {
    background-color: #0F5897;
    border: 1px solid #0F5897;
  }
</style>
<h1>Cat Photo Finder</h1> 
<p class="message box">
  The message will go here
</p>
<p>
  <button id="getMessage">
    Get Message
  </button>
</p>
3 Likes

Can anyone explain why there area double quotes (’" and "’) around the + val.imageLink + and what this means? Just can’t figure it out!

Thanks!

1 Like

It’s not that there are double quotes around + val.imageLink + … instead, there are double quotes around the strings to either side of + val.imageLink +. Those strings include a single quote '.

Your finished html needs to look like this, for example: <img src='http://someurl.com/image.jpeg'>. The url needs to be in quotes - that’s why each of the strings includes the single quote '. You have to include the single quote in the strings because it won’t be a part of the image url variable. When combined, the url ends up wrapped in quotes.

What the code snippet does is concatenate three things: a leading string, a variable and the terminating string. You could rewrite it like this:

var imgStart = "<img src = '";
var imgEnd   = "'>"
var imgLink  = "http://someurl.com/image.jpeg";

html += imgStart + imgLink + imgEnd;
9 Likes

Thank you, I finally understand :slight_smile: