Taking main inspiration from this W3 example, I developed a possible alternative and compact solution.
In the example linked is possible to see 3 different options:
- Filter only UL items
- Filter any item
- Filter any item with css animated effect
The simplest JS code is the following, that simply filter any kind of element thanks to $("#anyItemList *") selector:
$("#anyItemListInputFilter").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#anyItemList *").filter(function() {
let item = $(this).text().toLowerCase().indexOf(value) > -1;
$(this).toggle(item);
});
});
In case that desired filtering would be only for UL list, that selector could changed with $("#ulList li") (as in example)
If you want also to add css animation effect, there are some constraints:
- Needed a pre-defined
max-height in px (maybe not so much impacting if you set an enough taller one)
overflow-y:hidden;
So I was forced to declare:
#anyItemAnimatedList * {
transition:all 0.5s ease;
opacity:1;
max-height:500px;
overflow-y:hidden;
}
#anyItemAnimatedList ul {
list-style-position:inside;
}
#anyItemAnimatedList .hidden {
max-height:0;
opacity:0;
border:0;
}
Hiding effect is made with a combination of opacity and max-height css transitions, and border:0 is necessary to override button tag default browser style.
In addition, in case of OL and UL lists is necessary to set list-style-position:inside; due to a strange default behaviour shared by Firefox and Chrome that hide bullets in case of default list-style-position:outside.
For Firefox this is a known bug since 2003!!! but also Chrome has the same behaviour.