02-Variables

In this module, we'll set up variables to be used for DOM manipulation.

API Data

At the top of nyt.js, add the following code:

const baseURL = 'https://api.nytimes.com/svc/search/v2/articlesearch.json'; //1
const key = 'ADD-THE-KEY-FROM-YOUR-EMAIL-HERE'; //2
let url; //3

Let's talk about what we're doing: 1. Here we declare the baseURL of the API. This is the required API endpoint for the New York Times data. 2. Don't just mindlessly copy: You need to take the API Key that was emailed to you and put this in the value of the key variable. This will let the NYT know exactly what user is using their API. 3. We'll see later how we use the let url variable. We'll use it to make a dynamic search url.

References to DOM Elements

Next, we'll set up variables that reference all the DOM elements that we'll be manipulating:

//SEARCH FORM
const searchTerm = document.querySelector('.search');
const startDate = document.querySelector('.start-date');
const endDate = document.querySelector('.end-date');
const searchForm = document.querySelector('form');
const submitBtn = document.querySelector('.submit');

//RESULTS NAVIGATION
const nextBtn = document.querySelector('.next');
const previousBtn = document.querySelector('.prev');
const nav = document.querySelector('nav');

//RESULTS SECTION
const section = document.querySelector('section');

Remember what the querySelector() method does? The MDN docs define it like this: It returns the first Element within the document that matches the specified selector or group of selectors. If no matches are found, null is returned.

If you reread through the html file, you'll see the .search class, the .start-date class, the form element, etc. All of the above variables correspond something that is inside of our .html file already. Do yourself a favor and glance through the html code.

Let's use the nav variable to set the initial style to none:

nav.style.display = 'none';

Eventually, we'll have pagination, which is a way to toggle through the page results. In the code above, we are using the nav variable and setting a css style of display to 'none'. We do this to hide the "Previous"/"Next" navigation when the page loads, before we do a search. We don't want it turned on immediately when there are no results to page through.

Pagination and Display

Let's also add a few take care of some pagination issues that will come up later. Set the pageNumber to 0 by default, and set displayNav to false to further ensure that it won't be visible until we want it to be:

let pageNumber = 0;
let displayNav = false;

We actually won't deal with these variables again for a little while.

Last updated