Home > Web Front-end > CSS Tutorial > How to Display Tooltips Only When Text is Ellipsis-Truncated?

How to Display Tooltips Only When Text is Ellipsis-Truncated?

Linda Hamilton
Release: 2024-11-07 11:50:03
Original
956 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template