Facebook Friend Selector script with Jquery
In this post we'll talk about how we can create a filter to show only certain blocks (div, span, p, etc.) that contain specific words.
The filter can be used like a facebook friends selector, but their applications can go beyond just that.
To create the necessary plugins are:
Through each function of jquery, we read the divs with the same class name and from there we look for the name or value we want.
The first step is create our divs structure. It's important to mention that all divs must have the same name class and a different id.
This is a example of the structure:
Cuatro
Seis
Siete
Cuatro
Diez
Once
Siete
Catorce
Once
Mil
We need to add a text field, that we'll use like a search tool.
Now, it's the moment to create our script.
What we do is the following:
- When you release a key, you must read the text field (KeyUp event of Jquery). If we use other methods such as keydown, what we read in the text field will be delayed by a letter.
- We obtain the value of the text field.
- With the each function, we going to read every div with the same class name, in this example will be "cont".
- We compair the text of the div with the value of the text field.
- If the div doesn't contains that we looking for, we hide the div. We can do this with the ID of the div that we obtain with the name of the class. In other way, we show the div.
$("#buscar").keyup(function () {
var search = $(this).val();
$('.cont').each(function(index, Element) {
var currentId = $(this).attr('id');
if( search != '' ){
if( $(Element).text().toLowerCase().indexOf( search ) == "-1" ){
$("#" + currentId).hide('');
}else{
$("#" + currentId).show('');
}
}else{
$("#" + currentId).show('');
}
});
}).keyup();
By working with many divs can cause problems in IE, comes to lock the script.
There are other ways to perform the same functionality using JSON. That will be shown in other entries.
