Show tooltip only when text overflows
Using jQuery and jQuery UI, or jQuery only, or vanilla JavaScript.
HTML
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<p><code>title</code> attribute set on <code>display: block;</code> elements</p>
<div class="block-container" title><span>Short Text</span></div>
<div class="block-container" title><span>Long Text Really Really Really Long</span></div>
<p><code>title</code> attribute set on <code>display: inline;</code> elements</p>
<div><span class="inline-container" title>Short Text</span></div>
<div><span class="inline-container" title>Long Text Really Really Really Long</span></div>
CSS
div, span {
border: 1px solid;
}
div {
width: 15ch;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
JavaScript
/*
// 1. Using jQuery and jQuery UI
$(document).tooltip({
//items: '[title]', // this is the default, thus commented out
content: function () {
// The container should be a `display: block` element
// as overflow means a `display: inline` element excedes the size of a `display: block` element
var container = this.className === 'block-container' ? this : this.parentNode;
var title = this.title || this.getAttribute('data-title') || this.textContent;
var overflowed = container.scrollWidth > container.clientWidth;
// Return an empty string as content won't show the tooltip
return overflowed ? title : '';
}
})
*/
/*
// 2. or using jQuery only
$(document)
.on('mouseover', '[title]', function () {
var container = this.className === 'block-container' ? this : this.parentNode;
var title = this.title || this.getAttribute('data-title') || this.textContent;
var overflowed = container.scrollWidth > container.clientWidth;
this.title = overflowed ? title : '';
})
.on('mouseout', '[title]', function() {
this.title = '';
});
*/
// 3. or using vanilla JavaScript
document.addEventListener('mouseover', function(event) {
var target = event.target;
// Check support for matches() at <http://caniuse.com/#feat=matchesselector>
if (!target.matches('[title]')) return;
var container = target.className === 'block-container' ? target : target.parentNode;
var title = target.title || target.getAttribute('data-title') || target.textContent;
var overflowed = container.scrollWidth > container.clientWidth;
target.title = overflowed ? title : '';
});
document.addEventListener('mouseout', function(event) {
var target = event.target;
// Check support for matches() at <http://caniuse.com/#feat=matchesselector>
if (!target.matches('[title]')) return;
// 'mouseout' event fires even when move from parent to child element
if (event.relatedTarget.parentNode === target) return;
target.title = '';
});