Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <h1>NYT Top Stories</h1>

<p>Here are today's top stories from <a href="https://www.nytimes.com">The New York Times</a>.</p>

<div id="app">
  <p>
    <b>Fetching today's top stories...</b>
  </p>
</div>
              
            
!

CSS

              
                * {
  box-sizing: border-box;
}

body {
  width: 88%;
  max-width: 40rem;
  margin: 1rem auto;
  font: 1.25rem/1.5 Arial, Helvetica, sans-serif;
  color: #222;
}

h1,
h2,
h3 {
  line-height: 1.25;
  font-family: Georgia, 'Times New Roman', Times, serif;
}

:focus {
  outline: .125rem dotted currentColor;
  outline-offset: .25rem;
}
              
            
!

JS

              
                //
// Variables
//

// Get the #app element
const app = document.querySelector('#app');

// Store the API endpoint
const endpoint = 'https://nyt.barker.workers.dev';

// Store the desired categories
const categories = ['food', 'movies', 'technology'];


//
// Functions
//

/**
 * Get the JSON data from a Fetch request
 * @param {Response} response The Response object
 * @returns {Promise} The JSON data or the rejected response
 */
function getJSON (response) {
  return response.ok ? response.json() : Promise.reject(response);
}

/**
 * Sanitize and encode all HTML in a user-submitted string
 * {@link https://portswigger.net/web-security/cross-site-scripting/preventing}
 * @param {String} str The user-submitted string
 * @returns {String} The sanitized string
 */
function sanitizeHTML (str) {
  return str.replace(/[^\w. ]/gi, function (c) {
    return '&#' + c.charCodeAt(0) + ';'
  });
}

/**
 * Build the HTML string for a single story
 * @param {Object} story The story object
 * @returns {String} An HTML string
 */
function buildStory (story) {
  return `
    <article>
      <h3>
        <a href="${sanitizeHTML(story.url)}">
          ${sanitizeHTML(story.title)}
        </a>
      </h3>
      <p>
        <b>
          Last updated:
        </b>
        <time datetime="${sanitizeHTML(story.updated_date)}">
          ${sanitizeHTML(new Date(story.updated_date).toLocaleString())}
        </time>
      </p>
      <p>
        ${sanitizeHTML(story.abstract)}
      </p>
    </article>
  `;
}

/**
 * Build the HTML string for a single category
 * @param {Object} data The API data
 * @returns {String} An HTML string
 */
function buildCategory (data) {
  return `
    <article>
      <h2>${sanitizeHTML(data.section)}</h2>
      ${data.results.slice(0, 5).map(buildStory).join('')}
    </article>
  `;
}

/**
 * Make a Fetch request for the given category
 * @param {String} category The category
 * @returns {Promise} A Fetch request
 */
function fetchCategory (category) {
  // Options for the request
  const options = {
    method: 'POST',
    body: JSON.stringify({ category })
  };

  // Return the request
  return (
    fetch(endpoint, options)
      .then(getJSON)
      .then(buildCategory)
  );
}

/**
 * Join the category strings and add them to the DOM
 * @param {String[]} categories An array of HTML strings
 */
function showCategories (categories) {
  app.innerHTML = categories.join('');
}

/**
 * Add an error message to the DOM
 */
function showError () {
  app.innerHTML = `
    <p>
      <strong>
        Sorry, there was a problem fetching today's top stories. You can still view them using the link above.
      </strong>
    </p>
  `;
}

/**
 * Add the first five stories from each category to the DOM
 */
function getStories () {
  // Create an array of Fetch requests for the categories
  const requests = categories.map(fetchCategory);

  // This will resolve once ALL the requests have resolved
  const categoryStrings = Promise.all(requests);

  // Join the resolved array and add it to the DOM
  categoryStrings.then(showCategories).catch(showError);
}


//
// Inits & Event Listeners
//

// Add the first five stories from each category to the DOM
getStories();
              
            
!
999px

Console