I set out on a journey to create an iTunes-like search using Javascript. I learned about jQuery, and with some help from people on StackOverflow, I was successful.
I’ve come back here to share with you a very simple way to create a dynamic hide/show list based on the user input.
Let's search!
The entirety of the tutorial code can be found here.
And a JSFiddle for it is here!
First, create a simple Div Layout with some text in the divs and search bar above it.
CSS:
Second, you will make a script utilizing jQuery. Remember the title says this is a Dynamic Search, meaning (for us) we want to update the search with each key typed:
Note: Need a selector refresher?
Then we will set a variable to the value in #searchfield:
To ensure we show all the divs in our list when there is nothing in the searchfield we create an if statement based on the length of our new variable (str):
Last, we do the actual hiding of the divs if the length of str is not 0:
The
div:contains()anddiv:not(:contains())statements are what set the conditions. It’s essentially an if statement. They search the text contained within the div, not the div attributes. If you want to search a deeper div structure you can use more than one selector in the script’s jQuery statements like so:Replace the script statement you already have to give it a try.
Note: The nesting structure of your divs must match that in your selector.
And that’s essentially it. If you have tips to improve this, know how to change it to a case insensitive search, or anything else you can think of, please let me know!
Thanks to MrXenoType I have learned case insensitivity for the :contains function.
To create a case insensitive search for this project simply add:
This creates a pseudo for the contains function. Place this code above your other script (within the same script) to make true for only this script.