Chelseawillrecover
Chelseawillrecover

Reputation: 2644

Using JQuery to pass JSON data into DIVs

Hi I have the following recommendation from an expert and I am trying to rebuild my Code based on these recommendations:

This is the new Code I am working on:

var page = 1;
$(document).on('click', '#devotionclick', function blogs() {
    $('#postlist').empty();
   // $('#category').prepend('<div class="categories_listing"><span data-type="blogs" data-category="5">Blog Category</span></div>');
    var count = "5";
    var result = $.getJSON('http://howtodeployit.com/api/get_posts/?count=' + count + '&page=' + page, function (data, status) {
        if (data !== undefined && data.posts !== undefined) {
            $.each(data.posts, function (i, item) {    
                var str = item.title;

                $('#postlist').append('<div class="article"' + item.id + '"><div>' + item.title + '</div><div>' + item.excerpt + '</div></div>');
                if (data !== undefined) {
                    $('#stats').text('Page ' + data.query.page + ' of ' + data.pages + ' | Total posts ' + data.count_total + '');
                }
                if (data.query.page < data.pages) {
                    $("#loadmore").show();
                } else {
                    $("#loadmore").hide();
                }
            });
            page++;
        }
    });
    $('#postlist').append('<div id="loadmore"><div id="stats"></div><div id="loadmore">load more</div></div>');
    $('#loadmore').click(blogs);
});

HTML:

!-- Page: home -->
    <div id="home" data-role="page">
        <div class="ui_home_bg" data-role="content"></div>
        <div data-role="listview">
            <a href="#devotion" id="devotionclick" data-role="button">Daily Devotional Messages</a>
        </div><!-- links -->
    </div><!-- page -->

<!-- Page: Daily Devotional Messages -->
    <div id="devotion" data-role="page">
        <div data-role="header" data-position="fixed">
            <h2>Daily Devotional Messages</h2>
        </div><!-- header -->
        <div data-role="content" id="postlist"> </div><!-- content -->
    </div><!-- page -->

The issues I am having right now is:

  1. When I click on the Button it Loads the first 5 Posts but when I click on the 'load more' Text, it Loads the next 5 rather than Appending to existing Lists.

  2. The Lists isn't displayed as a Listview item which should be clickable

Upvotes: 0

Views: 928

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388406

Problem 1
It is because of $('#postlist').empty(); in the click handler.... you are removing all items from the page before loading new items. Remove this

Upvotes: 1

Related Questions