JAY NATHAN
JAY NATHAN

Reputation: 79

Javascript: How can I count the number of lines of a text element inside a DOM element such as <li>

My question is, if there is a way in javascript to count the number of lines of an element such as :

<li classname="link-link"> Lorem Ipsum has been the industry's standard dummy text ever
since the 1500s, when an unknown </li>

With no line length being set. This example could be in 2,3 or 4 lines. There are similar questions to this, but none gave the answer I was looking for.

Upvotes: 2

Views: 3556

Answers (2)

team meryb
team meryb

Reputation: 113

This code works for any Kind of elements:

HTML:

<div><span class="Text" id="g1" >
                This code works for any Kind of elements: bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli </span>
        </div>

CSS:

.Text{font-size: 28px;}
@media screen and (max-width: 780px) {
            .Text{font-size: 50px;}
        }

JAVASCRIPT:

function getStyle(el,styleProp)
{
    var x = el;
    if (x.currentStyle)
        var y = x.currentStyle[styleProp];
    else if (window.getComputedStyle)
        var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
    return y;
}
function calculateLineHeight (element) {

  var lineHeight = parseInt(getStyle(element, 'line-height'), 10);
  var clone;
  var singleLineHeight;
  var doubleLineHeight;

  if (isNaN(lineHeight)) {
    clone = element.cloneNode();
    clone.innerHTML = '<br>';
    element.appendChild(clone);
    singleLineHeight = clone.offsetHeight;
    clone.innerHTML = '<br><br>';
    doubleLineHeight = clone.offsetHeight;
    element.removeChild(clone);
    lineHeight = doubleLineHeight - singleLineHeight;
  }

  return lineHeight;
}

function getNumlines(el){return Math.ceil(el.offsetHeight / calculateLineHeight (el))}
console.log(getNumlines(document.getElementById('g1')))

Upvotes: 0

Chris
Chris

Reputation: 2465

You could get the height and line height then round that to get your answer.

HTML:

<li id="link-link"> Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown </li>

JS (Jquery):

var height = $("#link-link").height()
var fontSize = $("#link-link").css('font-size');
var lineHeight = Math.floor(parseInt(fontSize.replace('px','')) * 1.5);

console.log(Math.ceil(height / lineHeight));

Pure JS:

var el = document.getElementById('link-link');

var style = window.getComputedStyle(el, null).getPropertyValue('font-size');
var fontSize = parseFloat(style); 

var lineHeight = Math.floor(fontSize * 1.5);
var height = el.clientHeight;

console.log(Math.ceil(height / lineHeight));

JSFiddle w JQuery | JSFiddle with out JQuery

Upvotes: 2

Related Questions