Skip to content

Instantly share code, notes, and snippets.

@just3ws
Created April 14, 2011 17:55
Show Gist options
  • Save just3ws/920060 to your computer and use it in GitHub Desktop.
Save just3ws/920060 to your computer and use it in GitHub Desktop.
Toggles elements by their title as characters are typed into the text box.
// The character array as a queue was clever but poorly implemented and unnecessary.
// Instead, just read the query from the input.
// Also handles mouse driven content actions (cut, paste, etc).
$(function() {
var filter = function(query) {
var titlesSelector = "#content .show h3 a";
if (query == '') {
$(titlesSelector).closest(".show").show();
} else {
$("#content .show").closest(".show").hide();
$(titlesSelector + ":contains('" + query + "')").closest(".show").show();
}
}
var h = function(eventData) {
filter($(this).val().toLowerCase());
};
$("<input>", {
"placeholder" : "type to filter by title",
class: "search",
keyup: h,
focusout: h,
mouseleave: h
}).appendTo("#content h4");
}
// assumes that the title content is lowercase.
// I'm aware of the duplication of some functionality.
// this is just a POC for the work I'm doing on ccs. :)
var titlesSelector = "#content .show h3 a";
$(function() {
var characters = new Array();
$("<input>", {
"placeholder" : "type to filter by title",
class: "search",
keyup: function(eventData) {
if (eventData.keyCode == 8) {
characters.pop();
}
pattern = characters.join("");
showSelector = titlesSelector + ":contains('" + pattern + "')";
hideSelector = titlesSelector + ":not(:contains('" + pattern +"'))";
$(showSelector).parent().parent().show();
$(hideSelector).parent().parent().hide();
},
keypress: function(eventData) {
var newChar = String.fromCharCode(eventData.which).toLowerCase();
characters.push(newChar);
pattern = characters.join("");
showSelector = titlesSelector + ":contains('" + pattern +"')";
hideSelector = titlesSelector + ":not(:contains('" + pattern +"'))";
$(showSelector).parent().parent().show();
$(hideSelector).parent().parent().hide();
}
}).appendTo("#content h4");
}
@just3ws
Copy link
Author

just3ws commented Apr 14, 2011

This is a little POC I whipped up to filter sessions by title on the CCS sessions index page.

@thegrubbsian
Copy link

Can you post some example markup to go along with this for context.

@chrisjpowers
Copy link

Rather than both showing the positive matches AND hiding the negative matches, I think it might be more efficient to hide them all and then show the positive matches. Also, I'd suggest using the literal [] rather than new Array() -- literals are always a safer bet than the initialization equivalents because they actually have quirky differences.

@just3ws
Copy link
Author

just3ws commented Apr 14, 2011

@thegrubbsian even better(?) the code is up live at http://chicagocodecamp.com.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment