Reputation: 847
I'm working on a job listings page that shows results based on the combination of various filters. I want a "No matches" message to appear when there are no results for a set of filters, and I figured I'd just show/hide a p
element via a click
function based on the visibility of the job listing elements. Each job listing is contained within an li.requisition-item
; and I tried to test in two different ways for visibility based on other SO threads. This is what I have thus far:
$(".requisition-filter a").on("click", function() {
if ($('.requisition-item').is(":visible").length == 0 || $('.requisition-item').css('display') == 'none' ) {
$('p.no-results').show();
console.log('show alert');
}
else if ( $('.requisition-item').is(":visible").length || $('.requisition-item').css('display') == 'block' ) {
$('p.no-results').hide();
console.log('hide alert');
}
else {
$('p.no-results').hide();
}
});
Thus, I have a paragraph element with the class no-results
that should show/hide based on these conditions, but it the script does not behave as expected. The alert will (sometimes) show properly, but not "re-hide" appropriately when the filters reveal listings again. Any ideas what's going wrong here?
Upvotes: 0
Views: 3103
Reputation: 1172
In the attached solution, I faked the filtering out of items just by clicking the 'Filter out items' button (same as if I was clicking Russia). This runs a check for if any of the results are visible, and displays the no results message accordingly.
$("button.filter").click(function() {
$(".item").toggle();
checkResults();
});
function checkResults() {
var $items = $(".item");
if ($items.filter(":visible").length == 0) {
$(".message").show();
} else {
$(".message").hide();
}
}
.message {
display: none;
position: absolute;
width: 100px;
height: 100px;
border: 1px solid black;
left: 250px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="message">No results!</div>
<button class="filter">Filter out items</button>
<ul>
<li class="item">Item 1</li>
<li class="item">Item 2</li>
</ul>
Upvotes: 2