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%):