Skip to content

Instantly share code, notes, and snippets.

@Nitrodist
Last active February 28, 2021 21:29
Show Gist options
  • Save Nitrodist/83354e779d409f3ace65a76f4566a1e1 to your computer and use it in GitHub Desktop.
Save Nitrodist/83354e779d409f3ace65a76f4566a1e1 to your computer and use it in GitHub Desktop.
// With jQuery and data tag driven templating, wrap text with a tag to highlight the text
// such that this works:
//
// <p data-js-highlight-text="hello,">
// <span style="color: #009fff">Hello,</span> World
// </p>
//
// Extended examples with data attributes in your html:
//
// Set the data-js-highlight-text attribute. Before:
// <p data-js-highlight-text="hello,">Hello, World</p>
// After:
// <p data-js-highlight-text="hello,"><span style="color: #009fff">Hello,</span> World</p>
//
// **NOTE**
//
// See below for installation instructions as to how to highlight
// text in the context of your web app that's driven by javascript.
// http://stackoverflow.com/a/9795091
$.fn.wrapInTag = function (opts) {
// http://stackoverflow.com/a/1646618
function getText(obj) {
return obj.textContent ? obj.textContent : obj.innerText;
}
var tag = opts.tag || "strong",
words = opts.words || [],
regex = RegExp(words.join("|"), "gi"),
replacement = "<" + tag + ">$&</" + tag + ">";
// http://stackoverflow.com/a/298758
$(this)
.contents()
.each(function () {
if (this.nodeType === 3) {
//Node.TEXT_NODE
// http://stackoverflow.com/a/7698745
$(this).replaceWith(getText(this).replace(regex, replacement));
} else if (!opts.ignoreChildNodes) {
$(this).wrapInTag(opts);
}
});
};
// INSTALLATION INSTRUCTIONS
//
// onmount is an alternative to jquery ready + $("selector") abuse.
// The onmount lib allows a function to run once and only once against each instance
// of the css selector.
//
// Replace the onmount function call with a $("p").each call or document.querySelectorAll,
// or however else you want to run this javascript in your app's lifecycle in apps driven with react/vue.
//
// https://github.com/rstacruz/onmount
onmount("[data-js-highlight-text]", function () {
var highlight_phrase = $(this).data("js-highlight-text");
var color = $(this).data("js-highlight-text-color") || "#009fff";
$(this).wrapInTag({
words: [highlight_phrase],
tag: 'span style="color: ' + color + ';"',
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment