How can I parse for keyboard characters and display their graphical equivalent?
Problem
I'm working on a software development QA project. I'd like to achieve key styling result for ex( alt ) like SO does it. Is there any plug-in that parses text and finds all keys, replaces with key images / or with css3?
Any suggestions? Thanks in advance
Solution
I don't know of a plugin to do that, but you can easily create your own. The following plugin adds kbd
tags just like in Alvin Wong's example. Note that this is quite a naive approach and you might get unwanted markup.
(function($){
// List of keys
var keys = ["ctrl", "alt", "esc", "del", "end", "num"];
$.fn.keys = function(){
this.each(function(){
// Split text into words and remove line breaks
var text = $(this).html().replace(/(\r\n|\n|\r)/gm, "").split(" ");
// Compare every word to every key
for (var i = 0; i < text.length; ++i) {
for (j in keys) {
if (text[i].toLowerCase() == keys[j]) {
text[i] = "<kbd>" + text[i] + "</kbd>";
break;
}
}
}
$(this).html(text.join(" "));
});
};
})(jQuery);
You can then add arbitrary style in your CSS stylesheet. See SO's stylesheet for some inspiration... ;)
http://cdn.sstatic.net/stackoverflow/all.css
kbd {
/* ... */
}
Test it here: http://jsfiddle.net/BUxpt/
Discussion
There is currently no discussion for this recipe.
This recipe can be found in it's original form on Stack Over Flow.