So I’m working on a search page where I have a block that displays the next 10 items in a list. What I want to do is to hide this block when I reached the end of my list.
function loadMore() {
//Load the content
var urlPortion = searchQuery.split("?");
var urlString = "?hits=10&offset=";
var offset = 0;
var pageCounter = 1;
$(".box-footer").click(function () {
offset += 10;
pageCounter++;
var urlBuilder = urlPortion[0] + urlString + offset + "&" + urlPortion[1];
$.get(urlBuilder, function (data) {
var content = $(".search-result-list li", data);
$('.search-result-list').append(content);
});
});
//Visibility of "Show more"-bar
var textString = $(".search-result-totalhits").html();
var totalHitsString = /\d+/;
var totalHits = textString.match(totalHitsString);
var numberOfPages = (Math.ceil(totalHits/10));
if ((totalHits > 10) && (pageCounter < numberOfPages)) {
$(".p-sok .box-footer").show();
}
else {
$(".p-sok .box-footer").hide();
}
};
My problem here is that the last condition that does the actual check whether to display the block or not always remains true. I’m guessing that the variable “pageCounter” isn’t available outside the click function above, but I am not sure. I’ve tried to output the variable to the console in line 18 but it does not output anything.
Someone care to give me som hints?
You are correct that you are running into a problem with variable scope. The call back for the click event is called in a different context then the LoadMore function. LoadMore is just where you declare it not where it is actually run. If you want to be able to access the variable in both the callback function and LoadMore than you need to declare pageCounter as a global outside the LoadMore function. So something like:
That said I actually think you want to move everything after “//Visibility of “Show more”-bar” into the on click handler. I say that because you want to show or hide the header based on your current place in the list. That is going to update every time they click, right? If so, try something like: