JSFiddle - React, Tailwind, and code Playground

by Amal Das

HTML

<div alt="tooltip one">one</div>
<div alt="tooltip two; which is longer">two</div>
<div class="big">No tooltip here</div>
<div alt="wahey">And one more time...</div>

CSS

* {
    margin: 0;
    padding: 0;
    border: 0;
}
[alt] {
    width: 50%;
    float: left;
    background-color: red;
    margin-top: 20px;
    cursor: pointer;
}
[alt]:first-child {
    background-color: lime;
}
[alt=wahey] {
    background-color: blue;
    float: right;
}
#tooltip {
    position: absolute;
    background-color: yellow;
    padding: 2px 5px 2px 5px;
    margin: 10px;
    display: none;
}
.big { height: 1000px; background-color: #eee; }

JavaScript

var itemsToTooltip = $('[alt]');
    
    if (itemsToTooltip.length > 0) {
    // Create our tooltip element
        var tooltip = $('<div/>', {
            id: 'tooltip'
        }).appendTo('body');
    }
    
    itemsToTooltip.mousemove(function (e) {
        // Set tooltip content
        tooltip.text($(this).attr('alt'));
        var testLeft = itemsToTooltip.getBoundingClientRect().left;
        var testTop = itemsToTooltip.getBoundingClientRect().top;
        
        // Get full size (inc padding + margin) of tooltip
        var tw = tooltip.outerWidth(true);
        var th = tooltip.outerHeight(true);
        
        var x = e.pageX;
        var y = e.pageY;
        var w = $(document).width();
        var h = $(document).height();
        
        // If the tooltip is going to overflow the page, keep it inside
        //debugger;
        if (x + tw >= w) {
            x = w - tw;
        }
        if (y + th >= h) {
            y = h - th;
        }
        x = (x - Math.round(tw/2));
    
        // Show the tooltip and set it's position
        tooltip.fadeIn('fast').css({
            'left': testLeft,
            'top': testTop
        });;
    });
    
    // When we mouse off we should hide the tooltip (and remove its contents)
    itemsToTooltip.mouseout(function () {
        tooltip.stop().fadeOut('fast', function() {
            $(this).text('')
        });
    });