JSFiddle - React, Tailwind, and code Playground

by samdelagarza

HTML

<span class='tooltip' data-tooltip="Surprise me, I'm here!">
    hello world
</span>

<div class='tooltip' data-tooltip="New surprise, hello!">
    hello world 2
</div>

JavaScript

$(function () {
    var tooltipCache = {},
    getBuiltTooltip = function ($el) {
        var msg = $el.attr('data-tooltip'),
        node;

        if (tooltipCache[msg]) {
            return tooltipCache[msg];
        } else {
            node = $('<span>', { text: msg, style: 'background-color:#fff;border: 1px solid #666;position:absolute;top:30px;left:65px;padding:2px' });
            tooltipCache[msg] = node;
            return tooltipCache[msg];
        }
    },
    showTooltip = function (e) {
        var $el = $(e.target), 
            node;
        
        // Does the tooltip already exist as a child?
        if ($el.find('span').length > 0) {
            console.log('found, only show tooltip');
            $el.find('span').show();
        } else {
            console.log('not found, need to build tooltip');
            node = getBuiltTooltip($el);
            $el.append(node);
        }
    },
    hideTooltip = function (e) {
        $(e.target).find('span').hide();
    },
    createTooltip = function (item) {
        $(item).on('mouseover', showTooltip);
        $(item).on('mouseout', hideTooltip);
    };

    $('.tooltip').each(function (index, item) {
        createTooltip(item);
    });
});