Skip to content

Instantly share code, notes, and snippets.

@egardner
Created January 17, 2017 04:06
Show Gist options
  • Save egardner/e99e5165950835ad7862ca34d8268c02 to your computer and use it in GitHub Desktop.
Save egardner/e99e5165950835ad7862ca34d8268c02 to your computer and use it in GitHub Desktop.
Feedr AJAX request example
//
// URLs: let's stash these here and access later
//
var breitbartUrl = 'https://api.rss2json.com/v1/api.json?rss_url=http%3A%2F%2Ffeeds.feedburner.com%2Fbreitbart';
var foxUrl = 'https://api.rss2json.com/v1/api.json?rss_url=http%3A%2F%2Ffeeds.foxnews.com%2Ffoxnews%2Fpolitics';
var nytUrl = 'https://newsapi.org/v1/articles?source=the-new-york-times&sortBy=top&apiKey=08d58f2f94b0426e856bb17cb5a7657b'
$(document).ready(function(){
//
// Let's stash our container div as a variable here so we can access it
// wherever we need to below.
//
var articleContainer = document.getElementById('main');
// Get the Fox News data and do some work in the callback. If we want to show
// Fox results by default before the user has selected anything, then we can
// also use the callback as an opportunity to remove our loading indicator.
//
$.get(foxUrl, function(response) {
//
// Once your program has gotten to this point, it means the request has
// fired and you have some data. So if you include a loading div by default
// in your HTML page, this is where you can disable it. Do that before
// you start appending the results below.
//
// response.items is an array. Let's do something with each element of
// that array in a forEach() loop; "item" is the placeholder variable
// for our current array element.
//
response.items.forEach(function(item) {
//
// We want to build a DOM node for each item and then append that
// to our existing page structure. Handlebars makes it easy to do
// things like this but it can also be done manually. Let's start by
// creating variables for the data that we care about:
//
var title = item.title;
var link = item.link;
var imageUrl = item.thumbnail;
//
// Next we need to create dom nodes so we can append them to the existing
// document. If you use Handlebars, this is the part of the code you'll
// want to change. The vanilla JS API for this is kind of verbose sadly.
//
// 1. Create the top-level <article> element
var articleNode = document.createElement("article");
articleNode.setAttribute("class", "article");
//
// 2. Add the featuredImage section
var featuredImageNode = document.createElement("section");
featuredImageNode.setAttribute("class", "featuredImage");
articleNode.appendChild(featuredImageNode);
//
// 3. Add the actual image element and give it the thumbnail URL
var imageNode = document.createElement("img");
imageNode.setAttribute("src", imageUrl);
featuredImageNode.appendChild(imageNode);
//
// 4. Add the articleContent section
var articleContentNode = document.createElement("section");
articleContentNode.setAttribute("class", "articleContent");
articleNode.appendChild(articleContentNode);
var articleLink = document.createElement("a");
var articleTitle = document.createElement("h3");
var articleText = document.createTextNode(title);
articleLink.setAttribute("href", link);
articleContentNode.appendChild(articleLink);
articleLink.appendChild(articleTitle);
articleTitle.appendChild(articleText);
//
// 5. Add the impressions block
var articleImpressions = document.createElement("section");
articleImpressions.setAttribute("class", "impressions");
var impressionsCount = document.createTextNode("526");
articleNode.appendChild(articleImpressions);
articleImpressions.appendChild(impressionsCount);
//
// 6. Add the clearfix block
var clearFix = document.createElement("div");
clearFix.setAttribute("class", "clearfix");
articleNode.appendChild(clearFix);
//
// Our new articleNode element is just floating off in space at this point;
// we still have to hook it onto something that's actually on the existing
// page. Let's use our articleContainer element from the top of this file.
//
articleContainer.appendChild(articleNode);
//
// Each time the loop iterates, all of this code gets run again for the
// next element in the array.
});
});
});
@egardner
Copy link
Author

This is an example of how to grab data via a $.get request and then populate a series of DOM nodes with the responses. If you use Handlebars you can make the code a lot less verbose: you need to stash a handlebars template somewhere that has the desired structure (all the section elements, etc), and then compile it with your variables. This would save you a lot of the appendChild() lines, which get pretty repetitive for complex markup like what you are dealing with.

As an alternative, in 2017 you can stick a <template> tag right on your page in lieu of using Handlebars: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template

Additional Functionality

To swap out the content of the articleContainer each time the user clicks a different news source, you'll want to add an event listener on the source links in the nav bar; when clicked, they should call a function that does the following:

  1. Empties out the container via something like articleContainer.innerHTML = ''
  2. Fires a new $.get() request similar to the above but with a different URL, and then iterates over the responses and builds out the content the same way. Keep in mind that if the news is coming from a different API, you might have to change some property names.

Since adding all the DOM manipulation again would get very repetitive, I'd suggest using the <template> tag method described in the link above so you can keep your functions more DRY. Somewhere in your HTML file you can create a tag like this:

<template id"articleTemplate">
  <article class="article">
    <section class="featuredImage">
      <img id="article0-img" src="images/article_placeholder_1.jpg" alt="" />
    </section>
    <section class="articleContent">
      <a id="article0-a" href="#" ><h3 id="article0">
        test test
      </h3></a>
      <h6>Lifestyle</h6>
    </section>
    <section class="impressions">
      526
    </section>
    <div class="clearfix"></div>
  </article>
</template>

Then just swap out the content of these elements with your data from each item in your responses.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment