Not the most clearly crafted title I am afraid.
My website has a search page which intially loads the first 6 results of any query, then loads 6 more until the screen is full, or as the users scrolls down.
At the top of the page and I trying to add some filters to among other things, fade out any out of stock item results.
So, the code behind adds the class "outOfStock" to any item container for products which are out of stock. Very simple jQuery can then fade these out and toggle the button text:
$('#inStockOnly').click(function () {
var buttonText = $(this).html();
$('.outOfStock').fadeOut('slow');
$(this).html(buttonText == "Show All Items" ? "In Stock Only" : "Show All Items");
});
This is fine, except of course it only performs this action on items already displayed, so as the user scrolls down the page, the AJAX loads more results, but this filter does not apply to those results.
Of course, pressing the button again then toggles the fade incorrectly on half the items!
I have tried adding $('.outOfStock').css('display','none')
to the return of the AJAX success function, but that doesn't seem to work, even if it did, it would still show the results whilst they load and then hide them immediately afterwards, which is not the result I am aiming for.
Any suggestions on how I would force the un-loaded items to display:none
as they load, if the element inStockOnly
has been clicked before (or if it has the text Show All Items
)
Could you pass the checked or unchecked value of your button when you load the resources? Then you could only return those items that are of the appropriate status.
Obviously, the downside would be that they would not be in the markup for when the user changes their mind and toggles the button the other way. At which point you could make another round of requests for the out of stock items.
It also seems like you should be able to process it how you would like in the success function when the results are returned. I.e., in the process of displaying those items via AJAX, find out what the latest status is on the user's checked or unchecked status for 'in stock items' only. This might mean that you need to create a hidden element to keep track of whatever they have requested most recently.
Like this perhaps:
$.ajax({
url: url,
data: data,
success: function(data) {
// Load all the values onto the page however you were already doing
if ($("#hiddenElement").attr("showHidden") == "true") {
$('.outOfStock').hide();
}
}
});
Then you would need to populate that hidden value in your $('#inStockOnly').click function.
// toggle hidden element
($("#hiddenElement").attr("showHidden") == "true" ? $("#hiddenElement").attr("showHidden","false") : $("#hiddenElement").attr("showHidden","true"));