Home  >  Article  >  Web Front-end  >  How Can I Display A Tooltip Only When Ellipsis Is Active in HTML?

How Can I Display A Tooltip Only When Ellipsis Is Active in HTML?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-06 08:27:02348browse

How Can I Display A Tooltip Only When Ellipsis Is Active in HTML?

Determining Ellipsis Activation for Tooltip Display

In HTML, if content exceeds the specified width of an element, ellipsis (...) can automatically be applied, denoted as overflow text that is truncated and replaced by three dots. This article explores how to display a tooltip only when ellipsis is active.

Background

Consider the following HTML snippet:

<code class="html"><p>I have got a span with dynamic data in my page, with ellipsis style.</p>

<pre class="brush:php;toolbar:false">.my-class
{
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;  
  width: 71px;
}
<span id="myId" class="my-class"></span>
document.getElementById('myId').innerText = "...";

In this example, the content within the "myId" span will be dynamically updated, and the ellipsis style activates when the content overflows the specified width.

Adding a Tooltip

To add a tooltip to this element, we can utilize the "title" attribute:

<code class="html"><span id="myId" class="my-class" title="Full Content"></span></code>

Making the Tooltip Appear Only with Ellipsis

However, we want the tooltip to appear only when the content is long enough to activate ellipsis. To achieve this, we can bind a mouseenter event listener to the element and dynamically add the "title" attribute:

<code class="javascript">$('.mightOverflow').bind('mouseenter', function(){
    var $this = $(this);

    if(this.offsetWidth < this.scrollWidth && !$this.attr('title')){
        $this.attr('title', $this.text());
    }
});</code>

In this JavaScript code, we check if the element's offset width is less than its scroll width, indicating that the content overflows. If the "title" attribute is not yet set, we then add the full text of the element as the tooltip. This ensures that the tooltip is only displayed when ellipsis is activated.

The above is the detailed content of How Can I Display A Tooltip Only When Ellipsis Is Active in HTML?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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