Hey! I recently received some helpful advice from a coding expert, and now I'm in the process of restructuring my code based on these recommendations:
- When using $.each(), you have the option to return true or false. If you return false, the loop will stop.
- Avoid building HTML from concatenated strings as it can lead to XSS vulnerabilities. jQuery provides tools to safely build HTML content.
- In general, try to steer clear of using .html(), especially if you're already working with DOM elements.
- Absolutely avoid using inline event handlers like onclick. Always look for alternative solutions.
Here is the updated version of the code I'm currently 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 -->
Currently, I am facing the following issues:
Upon clicking the button, the first 5 posts load correctly. However, when I click on 'load more,' it loads the next 5 posts instead of appending them to the existing list.
The lists are not displayed as clickable Listview items as expected.