News content

The next part is revealing the news content.

Bakery news content

We need to change the template of each list item by adding the a data-news-id attribute. The value is set to the i that reflects the index of the loop.

Note: It is recommend to define an ID or any unique key for the news instead of using the array index like this example.

1var listItem = "<li><a data-news-id='" + i + "' href='#news-content'>" + news.title + "</a></li>";

Then, we define a click handler to the links with href to #news-content.

Inside the handler, it fetch the news ID (index) from the data-news-id attribute, get the news content by the ID, and construct the content page with the data.

There is only one news content page so the app re-construct this page every time when user clicks on newns link.

 1// News view
 2$('#news-list').delegate('a[href="#news-content"]', 'click', function(event){
 3  var newsId = $(this).data('newsId');
 5  console.log ("news id:", newsId);
 6  // load the news.
 7  // cache the content element.
 8  var contentElement = $('#news-content').find('[data-role="content"]');
 9  var newsData =[newsId];
10  if (newsData === undefined)
11  {
12    contentElement.html('Error loading news content.');
13  }
14  else {
15      var newsText = "<h2>" + newsData.title + "</h2>";
16      newsText    += "<strong>" + + "</strong>";
17      if (newsData.image != undefined)
18        newsText  += "<p><img src='" + newsData.image + "'></p>";
19      newsText    += "<p>" + newsData.content + "</p>";
20      contentElement.html(newsText);
21  }
23// End News view

What’s next? We’re going to take a look at “MomentJS”.

overlaied image when clicked on thumbnail

Makzan | Mobile web app dev with phonegap | Table of Content