Using jQuery and JSON to display content

August 22nd, 2012

In my previous post I showed you how to get some data from a JSON file and then add to a web page using jQuery (if you haven’t read that one, you should read it first so this makes sense). It was a good starting point but it wasn’t really something that you would use on a real site. So here’s a quick example that is closer to something you would actually build and it’s only a few lines more than the previous example.

First our HTML:

1
2
3
4
<div class="wrapper">
   <ul></ul>
   <div class="profile"></div>
</div>

We’ll create the links to our profiles and put them in the ul tag and then put the chosen profile inside the div with the class of profile. Pretty simple stuff and nothing you haven’t done before if you’ve use jQuery.

Our JSON:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
   "person": [
       {
           "firstName": "Clark",
           "lastName": "Kent",
           "job": "Reporter",
           "image": "clark_kent.jpg"
       },
       {
           "firstName": "Bruce",
           "lastName": "Wayne",
           "job": "Playboy",
           "image": "bruce_wayne.jpg"
       },
       {
           "firstName": "Peter",
           "lastName": "Parker",
           "job": "Photographer",
           "image": "peter_parker.jpg"
       }
   ]
}

And our JavaScript:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$(function() {

   var div = $('.profile');
   var ul = $('ul');
   var people = [];

   $.getJSON('people.json', function(data) {
       $.each(data.person, function(i, f) {
           people.push([f.firstName, f.lastName, f.job, f.image]);
           ul.append('<li><a href="#' + i + '">' + f.firstName + '</a></li>')
       });
       $('a').on('click', addContent);
   });

});

First we have the usual stuff, we’re grabbing the profile div and the ul in the DOM and we’re creating an array called people. Next we use the same $.getJSON and $.each functions we used last time but this time, instead of directly adding the dat we get from the JSON file to the web page, we store it in our people array so that we work with it. Next, we create the links for the profiles by appending them to the ul tag and setting the hash to be the same as the index in the array. Finally, we grab the anchor tags and add a click event that will fire a function called addContent. Of course, in a real site you’d be more specific than just grabbing all the anchor tags in the DOM.

Now let’s add the addContent function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
$(function() {

   var div = $('.profile');
   var ul = $('ul');
   var people = [];

   $.getJSON('people.json', function(data) {
       $.each(data.person, function(i, f) {
           people.push([f.firstName, f.lastName, f.job, f.image]);
           ul.append('<li><a href="#' + i + '">' + f.firstName + '</a></li>')
       });
       $('a').on('click', addContent);
   });

   function addContent(e) {
       e.preventDefault();
       var hash = this.hash.replace('#','');
       div.html('');
       div.append('<img src="images/' + people[hash][3] + '">');
       div.append('<p><b>Name:</b> ' + people[hash][0] + ' ' + people[hash][1] + '</p>');
       div.append('<p><b>Job:</b> ' + people[hash][2] + '</p>');
   }

});

We grab the hash value of the link that’s been clicked and get rid of the actual hash mark. We then clear out the existing HTML in the profile div. Finally we use append to add our content to the DOM. If you don’t understand what’s going on with the people array, it’s pretty basic stuff, so you might want to read up on arrays.

Why separate our HTML, our JavaScript and our data? In this example, it doesn’t really seem like a big deal but imagine a site with hundreds of lines of HTML and JavaScript. By putting our profile data into it’s own file we can update and edit it easier and not have to worry about accidentally messing up our JavaScript. And by dynamically creating the links to our content, we don’t have to touch the HTML when profiles are added or removed.

One Response to Using jQuery and JSON to display content

  1. Sara says:

    Hi Mike! Could you please elaborate on the hash value in jQuery? I’ve seen it mentioned in many places but it’s frustrating not to know what it exactly is and when to use it, I’d like a post from you that explains it because your explanations are clear and detailed.
    Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *