Home > Article > Web Front-end > How to Display Tooltips Only When Text is Ellipsis-Truncated?
Displaying Tooltips for Ellipsis-Truncated Text
When dealing with dynamic page elements that may overflow their designated display area, adding tooltips to provide context becomes essential. In such cases, it's desirable to only display tooltips when the ellipsis (...) appears to indicate truncated content.
Consider the following HTML markup:
<code class="html"><span id="myId" class="my-class">...</span></code>
With CSS styling that enables ellipsis for wide content:
<code class="css">.my-class { text-overflow: ellipsis; overflow: hidden; white-space: nowrap; width: 71px; }</code>
To add a tooltip to this element, we can leverage jQuery's mouseenter event to check if the element's width is less than its scroll width, indicating truncated content. Only then do we set the title attribute, ensuring the tooltip appears when the ellipsis is triggered:
<code class="javascript">$('.mightOverflow').bind('mouseenter', function(){ var $this = $(this); if(this.offsetWidth < this.scrollWidth && !$this.attr('title')){ $this.attr('title', $this.text()); } });</code>
By implementing this solution, tooltips will only be displayed when the content overflows and ellipsis activates, providing valuable context to the user without cluttering the interface when it's unnecessary.
The above is the detailed content of How to Display Tooltips Only When Text is Ellipsis-Truncated?. For more information, please follow other related articles on the PHP Chinese website!