Skip to content

Instantly share code, notes, and snippets.

@webdevs-pro
Created November 4, 2021 16:17
Show Gist options
  • Save webdevs-pro/00ea4f0d8fb78603ef4c125578c0a804 to your computer and use it in GitHub Desktop.
Save webdevs-pro/00ea4f0d8fb78603ef4c125578c0a804 to your computer and use it in GitHub Desktop.
function initDHtooltips() {
// tolltips
$( document ).on( 'mouseenter', '[data-dh-tooltip]', function() {
clearTimeout( $( this ).data( 'dh-tooltip-timeout-id' ) );
var prevTooltip = $( this ).find( '.tooltip' );
if ( prevTooltip.length > 0 ) return false;
$( this ).append( '<div class="tooltip"><div class="tooltip-wrapper"><span>' + $( this ).data( 'dh-tooltip' ) + '</span></div><div class="tooltip-trangle"></div></div>' );
var tooltip = $( this ).find( '.tooltip' );
var innerWidth = getInnerWidth( $( tooltip ).find( '.tooltip-wrapper > span' )[0] ) + 21;
$( tooltip ).find( '.tooltip-wrapper' ).css({
'width': innerWidth
});
var overflow = tooltip.offset().left + tooltip.width() - $( window ).width();
if( overflow > 0 ) {
var pos = overflow + 10;
$( tooltip ).find( '.tooltip-wrapper' ).css({
'transform': 'translateX(-' + pos + 'px)'
});
}
});
$( document ).on( 'mouseleave', '[data-dh-tooltip]', function() {
var element = $( this );
var timeoutId = setTimeout( function() {
element.find( '.tooltip' ).css( 'animation', 'none' ).fadeOut( 200, function() {
$( this ).remove();
} );
}, 200 );
element.data( 'dh-tooltip-timeout-id', timeoutId );
});
function getInnerWidth(element) {
var wrapper = document.createElement('span'),
result;
while ( element.firstChild ) {
wrapper.appendChild( element.firstChild );
}
element.appendChild( wrapper );
result = wrapper.offsetWidth;
element.removeChild( wrapper );
while ( wrapper.firstChild ) {
element.appendChild( wrapper.firstChild );
}
return result;
}
}
[data-dh-tooltip] {
position: relative;
display: inline-block;
padding-bottom: 5px;
cursor: pointer;
padding-left: 3px;
}
[data-dh-tooltip] .tooltip {
position: absolute;
top: -2px;
left: 50%;
transform: translate( -50%, -100% );
z-index: 10;
filter: drop-shadow( 0 0 1px #000 );
font-family: var( --e-global-typography-text-font-family );
animation: dhTooltipFadeIn 200ms forwards;
}
[data-dh-tooltip] .tooltip .tooltip-wrapper {
width: 300px;
max-width: 300px;
color: #222;
padding: 10px;
text-align: left;
border-radius: 10px;
font-size: 13px;
line-height: 1.4em;
background: #fff;
padding-bottom: 10px;
}
[data-dh-tooltip] .tooltip .tooltip-wrapper a {
text-decoration: underline;
}
[data-dh-tooltip] .tooltip .tooltip-trangle {
position: absolute;
bottom: 0;
left: 50%;
transform: translate( -50%, 50%) rotate( 45deg );
height: 10px;
width: 10px;
background-color: #fff;
}
@keyframes dhTooltipFadeIn{
from {
opacity: 0;
}
to {
opacity: 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment