Markdown-like functionality for tooltips
Problem:
Using Vanilla JavaScript I want to:
Change this:
<div>
<p>
Hello [world]{big round planet we live on}, how is it [going]{verb that means walking}?
</p>
<p>
It is [fine]{a word that expresses gratitude}.
</p>
</div>
To this:
<div>
<p>
Hello <mark data-toggle="tooltip" data-placement="top" title="big round planet we live on">world</mark>, how is it <mark data-toggle="tooltip" data-placement="top" title="verb means walking">world</mark>?
</p>
<p>
It is fine <mark data-toggle="tooltip" data-placement="top" title="a word that expresses gratitude">thanks</mark>.
</p>
</div>
so it looks visually like this:
is somehow similar to "markdown" edit functionalities.
Solution:
- Mark the strings to replace in a different way:
<p>It is fine *[thanks]{a word that expresses gratitude}*!</p>
- Initiate Bootstrap and tooltip functionality.
- Grab all paragraphs
var p = document.getElementsByTagName('p')
- Apply REGEX
tooltip = original.match(/(\{)(.*?)(\})/gi)[0].slice(1, -1);
hint = original.match(/(\[)(.*?)(\])/gi)[0].slice(1, -1);
- Change their inside-text
replaced = original.replace(/(\*)(.*?)(\*)/gi,
`<mark data-toggle="tooltip" data-placement="top" title="${tooltip}">${hint}</mark>`);
elem.innerHTML = replaced;
- Alltogether in one function:
[].forEach.call(p, elem => {
let original = elem.innerHTML;
let replaced, tooltip, hint
tooltip = original.match(/(\{)(.*?)(\})/gi)[0].slice(1, -1);
hint = original.match(/(\[)(.*?)(\])/gi)[0].slice(1, -1);
replaced = original.replace(/(\*)(.*?)(\*)/gi,
`<mark data-toggle="tooltip" data-placement="top" title="${tooltip}">${hint}</mark>`);
elem.innerHTML = replaced;
});
but I fail
Miserable when there is more paragraphs or when I just want to do it in an easy way with 2 pair of brackets instead of additional asterix. Fails also hen the innerTEXT has more phrases / words that should have the tooltip. Any ideas? Do you have any suggestions? Existing ways of doing it? Libraries? Scripts?