Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
Why is the Masonry Javascript package not initializing?

I am very new to Javascript and this is my first time using the Masonry package. I am trying to have pictures from Nasa's Astronomy Picture of the Day to display in a masonry grid and they do display, but not in the Masonry grid format and I cannot figure out why. What am I doing wrong? Thanks! (API Key replaced by XXXXXX for obvious reasons).

HTML:

<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <script src="https://unpkg.com/masonry-layout@4/dist/masonry.pkgd.js"></script>
    <script defer src="script.js"></script>
    <title>NASA Astronomy Picture of the Day</title>
  </head>

  <body>
    <header>
      <h1>NASA Astronomy Picture of the Day</h1>
    </header>
    <main>
      <div class="grid">
      </div>
    </main>
  </body>

</html> 

Javascript:

'use strict';

window.addEventListener('DOMContentLoaded', () => {
  const grid = document.querySelector('.grid');
  var msnry = new Masonry( grid, {
    // options
    itemSelector: '.grid-item',
    columnWidth: 200
  });
  
  const api = 'https://api.nasa.gov/planetary/apod?api_key=XXXXXXXXXXXXXXXXXXXXXXXXX&count=3';
  const xhr = new XMLHttpRequest();
  xhr.open('GET', api);
  xhr.onreadystatechange = function() {
    if (xhr.status == 200 && xhr.readyState == 4) {
      var response = JSON.parse(xhr.responseText);
      response.forEach(object => {
          let div = document.createElement('div');
          div.classList.add('grid-item');
          grid.appendChild(div);
          let img = object.hdurl;
          grid.lastChild.innerHTML = '<img src="' + img + '" alt="NASA Picture of the Day" >';
      });
    }
  };
  xhr.send();
});

Results (Zoomed to 50%):

enter image description here

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!