You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

59 lines
2.1 KiB

  1. (function($){
  2. /* Adapted from http://www.kryogenix.org/code/browser/searchhi/ */
  3. $.fn.highlightText = function(text, className) {
  4. function highlight(node) {
  5. if (node.nodeType == 3) { // Node.TEXT_NODE
  6. var val = node.nodeValue;
  7. var pos = val.toLowerCase().indexOf(text);
  8. if (pos >= 0 && !$.className.has(node.parentNode, className)) {
  9. var span = document.createElement("span");
  10. span.className = className;
  11. span.appendChild(document.createTextNode(val.substr(pos, text.length)));
  12. node.parentNode.insertBefore(span, node.parentNode.insertBefore(
  13. document.createTextNode(val.substr(pos + text.length)),
  14. node.nextSibling));
  15. node.nodeValue = val.substr(0, pos);
  16. }
  17. } else if (!$(node).is("button, select, textarea")) {
  18. $.each(node.childNodes, function() { highlight(this) });
  19. }
  20. }
  21. return this.each(function() { highlight(this) });
  22. }
  23. $(document).ready(function() {
  24. var elems = $(".searchable");
  25. if (!elems.length) return;
  26. function getSearchTerms(url) {
  27. if (url.indexOf("?") == -1) return [];
  28. var params = url.substr(url.indexOf("?") + 1).split("&");
  29. for (var p in params) {
  30. var param = params[p].split("=");
  31. if (param.length < 2) continue;
  32. if (param[0] == "q" || param[0] == "p") { // q= for Google, p= for Yahoo
  33. var query = decodeURIComponent(param[1].replace(/\+/g, " "));
  34. if (query[0] == "!") query = query.slice(1);
  35. var terms = [];
  36. $.each(query.split(/(".*?")|('.*?')|(\s+)/), function() {
  37. term = this.replace(/^\s+$/, "");
  38. if (term.length) {
  39. terms.push(term.replace(/^['"]/, "").replace(/['"]$/, ""));
  40. }
  41. });
  42. return terms;
  43. }
  44. }
  45. return [];
  46. }
  47. var terms = getSearchTerms(document.URL);
  48. if (!terms.length) terms = getSearchTerms(document.referrer);
  49. $.each(terms, function(idx) {
  50. elems.highlightText(this.toLowerCase(), "searchword" + (idx % 5));
  51. });
  52. });
  53. })(jQuery);