Mustache: Insert Dynamic Tooltip into Template

Date: 2016-04-04 |

**Problem: **I’m using Mustache to help with my HTML templating. I want to add a dynamic tooltip based on the data I pass in to my Mustache.render() function. How can I do this?

**Solution: **The simplest solution is to use Mustache in conjunction with HTML5’s built-in title attribute functionality. The title attribute causes a small pop-up box to appear over an element containing whatever information you place inside it.

Here’s a gist:

[https://gist.github.com/SIRHAMY/525ce1a1e33c0627b9f1]

Here’s an example of a static (non-dynamic) piece in action:

[http://codepen.io/SIRHAMY/pen/wGGaXP]

Gist Breakdown

If you’ve used Mustache before, you probably recognize the syntax. If not, here’s a quick rundown.

The {{#tooltipText}} and {{/tooltipText}} tags tell Mustache to use the code found within them if tooltipText is present in the data that was passed in. You can think of it as an if statement block that hinges on whether that property exists.

Within those two tags, you see the title attribute being set. This title attribute will appear as a small tooltip whenever you hover your mouse over the span. While not the most elegant solution visually, its simplicity means you can’t really go wrong and that it’s supported by most browsers -a win in my book.

The next tag you see is within the title attribute: {{tooltipText}}. This tells Mustache that we want it to insert the data held in the property “tooltipText” that was passed in to the renderer inside that title attribute field. We know this property exists, because we used the outside Mustache tags to check for its presence in the passed in data.

That should get you started.

If you have further questions or would like some more clarification, feel free to reach out.

Want more like this?

The best / easiest way to support my work is by subscribing for future updates and sharing with your network.