Is it possible in HTML to create an "intelligent" overflow effect where text is truncated and replaced with an ellipsis "..." followed by a link to view the full content?

I have a <div> that has a limited size, and I am looking for a way to display multiline text in it. If the text exceeds the available space, I would like to add "..." at the end along with a link to view the full content on another page.

Is there a way to achieve this using Javascript/CSS? I tried researching but couldn't find a clear solution.

It seems like there is a CSS property text-overflow: ellipsis;, but adding a link on the ellipsis might not be possible.


The answer provided here is close, but there are instances where only a part of the ellipsis appears if the text starts to overflow.


Library requirements: I am open to using jQuery (albeit reluctantly), but I would prefer a cross-browser solution that doesn't rely on any specific framework.

Answer №1

This example showcases a simple method to iterate through elements marked with the class .smart-overflow. It introduces a clickable a element with the class ellipsis-link only when the content is truncated. The attached link triggers an event listener that reveals the hidden content which was initially concealed using overflow: hidden. Please note that this solution is tailored for single-line text. For multiple lines and broader browser compatibility, refer to the alternative below.

var elements = document.querySelectorAll('.smart-overflow');
Array.prototype.forEach.call(elements, function (el) {
  var link = document.createElement('a');
  link.href = '#'; 
  link.className = 'ellipsis-link';
  
  if (el.offsetWidth < el.scrollWidth) {
    link.addEventListener('click', function (e) {
      e.preventDefault();
      el.classList.remove('smart-overflow');
    });
    el.appendChild(link);
  }
});
      
p {
  width: 200px;
  position: relative;
}
.smart-overflow {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
a.ellipsis-link {
  display: none;
}
.smart-overflow a.ellipsis-link {
  display: block;
  position: absolute;
  right: 0; 
  bottom: 0;
  width: 1.2em;
  height: 100%;
  cursor: pointer;
}
<p class="smart-overflow">No ellipsis.</p>
<p class="smart-overflow">This is a longer string of text which should have an ellipsis. This is a longer string of text which should have an ellipsis.</p>
<p class="smart-overflow">Another string of text which should have an ellipsis. Another string of text which should have an ellipsis.</p>

In the scenario above, implementing text-overflow: ellipsis necessitates the usage of white-space: nowrap for it to operate effectively, restricting its functionality to a single line of text.

If you require multi-line support, consider employing the following methodology for modern browsers. If encountering any issues, explore the jQuery-based solution below for comprehensive browser backing.

var elements = document.querySelectorAll('.smart-overflow');
Array.prototype.forEach.call(elements, function (el) {
  var link = document.createElement('a');
  link.href = '#'; 
  link.className = 'ellipsis-link';

  link.addEventListener('click', function (e) {
    e.preventDefault();
    el.classList.remove('smart-overflow');
  });
  el.appendChild(link);
});
      
p {
  width: 200px;
  position: relative;
}
.smart-overflow {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;  
  max-height: 2.2em;
  overflow: hidden;
  position: relative;
}
a.ellipsis-link {
  display: none;
}
.smart-overflow a.ellipsis-link {
  display: block;
  position: absolute;
  right: 0; 
  bottom: 0;
  width: 4.2em;
  height: 1.2em;
  cursor: pointer;
}
<p class="smart-overflow">No ellipsis.</p>
<p class="smart-overflow">This is a longer multi-line string of text which should have an ellipsis. This is a longer string of text which should have an ellipsis.</p>
<p class="smart-overflow">Another multi-line string of text which should have an ellipsis. Another multi-line string of text which should have an ellipsis.</p>

JQuery provides a multi-line approach with comprehensive browser coverage utilizing this library.

$('.smart-overflow').dotdotdot({
  ellipsis: '',
  wrap: 'word',
  callback: function(isTruncated, content) {
    var self = this;

    if (isTruncated) {
      $(this).append($('<a/>', {
        class: 'ellipsis-link',
        text: '...',
        href: '#',
        click: function(e) {
          e.preventDefault();
          $(this).remove();
          $(self).removeClass('smart-overflow is-truncated').trigger("destroy");
        }
      }));
    }
  }
});
p { width: 200px; }
.smart-overflow { max-height: 2.8em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jQuery.dotdotdot/1.7.4/jquery.dotdotdot.min.js"></script>
<p class="smart-overflow">No ellipsis.</p>
<p class="smart-overflow">This is a longer multi-line string of text which should have an ellipsis. This is a longer string of text which should have an ellipsis.</p>
<p class="smart-overflow">Another multi-line string of text which should have an ellipsis. Another multi-line string of text which should have an ellipsis.</p>

Answer №2

Looking for some amazing jQuery plugins to enhance your website? Take a look at these:

https://github.com/jjenzz/jquery.ellipsis https://github.com/rviscomi/trunk8

I once developed a piece of code that integrates trunk8 with ellipsis, creating responsive links in the process.

(function($, window, document, undefined) {

  'use strict';

  window.seeMore = function() {
    function addSeeMoreLinks() {
      $article.find('p').trunk8(options).each(function() {
        var $this = $(this);

        if (0 === $this.find('.trunk8').length) {
          $this.append(' <a href="#" class="seeMore">see more</a>.');
        }
      });
    }

    function removeSeeMoreLinks() {
      $article.find('p').each(function() {
        $(this).find('.seeMore').remove();
      });
    }

    function setupSeeMoreLinks() {
      addSeeMoreLinks();
      $(window).resize(function() {
        removeSeeMoreLinks();
        addSeeMoreLinks();
      });
    }

    var
      $article = $('.blogArticleList article'),
      options = {
        lines: 6,
        fill: '&hellip; <a href="#" class="trunk8">see more</a>.',
        tooltip: false
      };

    setupSeeMoreLinks();
  };

  if (window.addEventListener && $().trunk8) {
    window.seeMore();
  }

})(jQuery, window, document);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to surround values and keys with double quotes using regular expressions in JavaScript

I am in need of a valid JSON format to request ES. I currently have a string that looks like this: { time: { from:now-60d, mode:quick, to:now } } However, when I attempt to use JSON.parse, I encounter an error because my ...

Acquire the text within an anchor tag using JavaScript

Is it possible to invoke a search for all links on my Wordpress blog? I'm not sure if my idea is correct. Currently, I am using an Ajax call for another search on this site. How can I extract the text from a hyperlink HTML tag? For example: <a href ...

How can I best fill the HTML using React?

After attempting to follow various React tutorials, I utilized an API to fetch my data. Unfortunately, the method I used doesn't seem to be very efficient and the code examples I found didn't work for me. I am feeling quite lost on how to proper ...

Is there a way to modify the video height so that it aligns with the dimensions of the

I'm currently trying to adjust the background video to fit the parent div, but I am facing issues with adjusting its height within the media query. Any suggestions on how I can resolve this problem? HTML <div class="hero"> <video ...

The mysterious plugin "transform-runtime" has been detected in the ".babelrc" file located in "UsersPhpstormProjectseasy-essay"

After downloading a GitHub repository, I came across a file named .babelrc.json with the following contents: { "presets": [ "es2015", "stage-0" ], "plugins": [ "transform-runtime", "add-module-exports", "transform-decorators-lega ...

The CSS is not displaying correctly on Safari and Chrome browsers in Mac OS

I'm having trouble with CSS not loading properly on Apple devices for a website I made. Despite maintaining all media query statements and style sheets separately, the display is not correct in MAC OS safari and chrome. However, everything looks fine ...

Configuring Proxy Settings for WebpackDevServer

I need assistance setting up a proxy using WebpackDevServer in my React/Node chrome extension. Currently, my server is running on localhost:4000, and the React frontend is on localhost:5000. When trying to access the route /api/user/ticket using Axios, I ...

Dealing with a routing issue in node.js/express involving JavaScript and CSS

I'm facing an issue. I need to set up a route from localhost.../cars to localhost../bmw/x1 On the localhost../cars page, there's a button that, when clicked, should load localhost../bmw/x1 This is the JavaScript code I have: const express = req ...

Difficulty with Pomodoro clock's canvas ring function not working as expected

Hey everyone, good evening. I've been struggling with a particular section of code for quite some time now and could really use some help. When you check out the constructor at this.drawArc and then look into the prototype, I've printed a couple ...

When you hover over the image, the text will disappear

When I hover over the image of LTC, a thumbnail appears with text and a button. However, I do not want the text "LTC" to be shown when hovering over the image. <div class="col-md-4"> <div class="view view-eighth"> <div class=" ...

Tips for retrieving information from a highstock chart

Imagine I have a sample highstock chart on my website, similar to the one at this link. Is there a way to extract the data from the chart itself, even if the data used for creating the chart is not accessible to others? <img src="http://www.highchart ...

Is there an issue with the functioning of Angular routing?

I've been working on setting up routing in AngularJS and it seems like the server is running smoothly. However, I'm facing an issue with the angular routing not functioning correctly; only the main.html page loads in ng-view, while second.html do ...

Stylish HTML table with personalized CSS styling

Can anyone help me figure out how to properly format a table using HTML and CSS? I've been struggling with this task for hours... I'm having trouble organizing the rows in the table to match the layout shown in the image below. All items should b ...

How do I disable the hover and click highlighting effect on a div in Vuetify using v-on in Vue2?

Currently, I have implemented a Vuetify VListItem in a NavigationDrawer with an on click listener that displays a menu in the div below. The menu is functioning properly - opening and closing as expected. However, it highlights on hover/click which I wou ...

GSAP also brings scale transformations to life through its animation capabilities

I have an SVG graphic and I'm looking to make four elements appear in place. I've been using GSAP, but the elements seem to be flying into place rather than scaling up. Here's the code snippet I've been using: gsap.fromTo( ...

Ways to improve the transition of a <video> background using CSS

My webpage features a unique 10-second video wallpaper achieved using only pure CSS. Below is the code I used: <style> video#bgvid { position: fixed; right: 0; bottom: 0; min-width: 100%; min-height: 100%; width: auto; he ...

JQuery enables nested sorting functionality

I need to enable the sortable feature specifically for the charts. Index.cshmtml <div id="sortable" class="col-lg-9"> <div class="col-lg-12 col-md-12 padding hidden" id=@($"chartNumber{Model.Charts[ ...

Is there a glitch in the Selenium Java CSS Selector functionality?

Everything seems to be working smoothly with that code! It successfully locates and clicks on my button within the span tag. driver.findElement(By.cssSelector("span[id$=somePagesCollection] a")).click(); However, after clicking the button, an input field ...

Problem with React Native Camera: Camera display is not functioning correctly - React-Native-Vision-Camera Error

Hey there! I could really use some help with a tricky situation I'm facing in my React Native app, specifically regarding camera integration. Here's the scoop: The Issue: I'm working on a video recording application using React Native that ...

Different Approaches for Handling User Interactions in Angular Instead of Using the Deferred (Anti-?)Pattern

In the process of developing a game using Angular, I have implemented the following mechanics: An Angular service checks the game state and prompts a necessary user interaction. A mediator service creates this prompt and sends it to the relevant Angular c ...