https://jsfiddle.net/mvuy7q60/

Using JavaScript (and jQuery). How can I assure that there's only one line shown (instead of entire content of item), and if it's longer than one line, end first line on "..."?

Something like this: https://jsfiddle.net/tt9psxz3/

Dani AI

Generated

As asked for a JavaScript/jQuery approach and pointed out a pure-CSS solution, a short note: prefer the CSS option when it fits the layout because it is simpler and far cheaper at runtime. When you need more control (preserve exact word breaks, run after web fonts load, support very old browsers, or you must preserve markup differently), a small JS fallback does the job reliably.

The snippet below is a compact jQuery routine that measures visible width, uses a binary search over the text length to find the longest substring that fits, and replaces the element text with that substring plus "...". It copies key font properties to an off-screen measurer for accurate sizing.

(function($){
  $.fn.clampToOneLine = function(opts){
    var settings = $.extend({ellipsis: '...', preserveWords: true}, opts || {});
    var $body = $(document.body);

    return this.each(function(){
      var $el = $(this);
      var full = $el.text();
      if (!full) return;

      var $meas = $('<span>').css({
        position: 'absolute', visibility: 'hidden',
        whiteSpace: 'nowrap', left: '-9999px', top: '-9999px'
      }).appendTo($body);

      // copy font-ish styles so measurement matches rendering
      ['fontFamily','fontSize','fontWeight','fontStyle','letterSpacing','textTransform'].forEach(function(p){
        $meas.css(p, $el.css(p));
      });

      var maxW = $el.width();
      if ($meas.text(full).width() <= maxW) { $meas.remove(); return; }

      var low = 0, high = full.length, best = '';
      while (low <= high) {
        var mid = Math.floor((low + high) / 2);
        var cand = full.slice(0, mid) + settings.ellipsis;
        $meas.text(cand);
        if ($meas.width() <= maxW) { best = cand; low = mid + 1; }
        else { high = mid - 1; }
      }

      if (settings.preserveWords) best = best.replace(/\s+\S*$/, '') || full.slice(0, Math.max(0, high)) + settings.ellipsis;
      $el.text(best);
      $meas.remove();
    });
  };
})(jQuery);

Usage: $('.your-selector').clampToOneLine();

Practical tips: run this after web fonts load (fonts can change widths), debounce calls on window resize, and note this replaces inner HTML with plain text — preserving nested markup requires a more complex text-node-aware routine. Where possible, use the CSS approach first and use this JS only for the edge cases.

Something like this should do the trick ...

div {
    text-overflow: ellipsis;
    overflow-x: hidden;
    white-space: nowrap;
}
commented: That escalated quickly. +4
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.