I’m a newbie with jQuery Mobile and I’m working with a list that is dynamically generated with ajax. Now I had some help to get this to load certain amount of items then with a “Load More” button to populate more items into this list. I have a few issues I can’t seem to figure out.
- I can’t get the “Load More” to append to the bottom
2 The “Load More” button appends multiple times in my list when clicked. It keeps the last button clicked in place then adds a new one further down.
Here is my code:
This is what is generating content on page load
function runBrowse() {
//Check if all fields have a value
$.ajax({
url: "http://www.example.com",
data: {firstName: "", middleName: "", lastName: "", resultSize:10},
success: browseSuccess,
});
}
function runBrowseContinue(restart) {
//Check if all fields have a value
$.ajax({
url: "http://www.example.com",
data: {restartLine: restart, resultSize:10},
success: browseSuccess,
});
}
function browseSuccess(browseResults){
$.mobile.changePage('#results');
restartLine = browseResults.restartLine;
jQuery.each(browseResults.people,handlePerson);
}
//Usage getMoreData(browseResults.restartLine);
function getMoreData(restartLine){
if(restartLine){
runBrowseContinue(restartLine);
}
}
function handlePerson(index, value) {
var output = '';
// Add these returns to listview
output += '<li>' + '<h3>' + value.name + '</h3>' + '<p>' + value.height + '</p>' + '<p>' + value.weight + 'lbs.' + '</p>' + '</li>';
$('#listview').append(output).listview('refresh');
}
This is the Load More code
$loadMore = $('ul').children('.load-more');
$loadMore.bind('click', function () {
var out = [];
out.push(getMoreData(restartLine));
$('ul').append(out.join('')).append($loadMore).listview('refresh');
});
This is my HTML
<ul data-role="listview" class="listContent" id="listview">
<li class="load-more"><a href="#">Load More</a></li>
</ul>
</div>
Thanks for any help 🙂
Screen shot of this:
From your screenshots it appears as though the
handlePersonfunction is adding more “people” to the list without moving the “Load More” button to the bottom, which will account for having list-items below the “Load More” button.When you append a DOM element that already exists, jQuery will move it to the new location and remove it from the old: http://api.jquery.com/append
I would like to warn against this however. This makes two DOM manipulations for every index (“person”). It would be better to buffer all of the list-item output, and append it at once, which will take a slight re-flow of your code:
As you can see it would be easy to just remove the
handlePerson()function all together and place it’s code inside the$.each()loop in thebrowseSuccess()function.