Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

215
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda