JSFiddle - React, Tailwind, and code Playground
by nevkatz
CSS
span{color:red}
.tooltip {
position: relative;
}
.tooltip:hover:after{
padding: 3px 6px;
background: red;
color:#fff;
content: attr(data-tooltip);
position: absolute;
left: 0px;
top: 20px;
}
JavaScript
var tooltips = {
"Size" : "The Size of a Unit is controlled by the Color",
"Color" : "bar",
"Time and Size" : "foo"
};
var p = "Here we have something of Size 20 and Color red. it's very important that the Time and Size of the work and kept Time and Size in sync.";
function replaceTooltips(str, tooltips) {
//copy from https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
function escapeRegExp(string) {
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
var keys = [];
for ( var k in tooltips) {
keys.push(escapeRegExp(k));
}
//create a regexp like (Size)|(Color)|(Time and Size)
var ptn = new RegExp('(' + keys.join(')|(') + ')', 'g');
str = str.replace(ptn, function(mat) {
if (!tooltips[mat]) {
return mat;
}
return '<span class="tooltip" data-tooltip="' + tooltips[mat].replace(/"/g, '"') + '">' + mat + '</span>';
});
return str;
}
var html = replaceTooltips(p, tooltips);
console.log(html);
document.body.innerHTML = html;