Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to detect if text is longer than one line in my div? [duplicate]

I have a div with some text in it that initially doesn't wrap and shows an ellipsis but I want to give the user the ability to click a read more option and then expand the div to show the entire piece of text.

However I want to be able to detect if the text is small enough to fit in the div without needing to expand it from one line and if so hide the show more option.

Here is a link to a modified JS Fiddle I have been working off:

http://jsfiddle.net/M2APS/44/

And the code from it:

$(document).bind('pageshow', function() {
  $(".text-size").click(function() {
    $(".ui-li > div").toggleClass("less");
    if ($(".text-size").html() == "Read more...") {
      $(".text-size").html("Read less...");
    } else {
      $(".text-size").html("Read more...");
    }
  });
});
.less {
  word-wrap: break-word;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.more {
  white-space: normal;
}

.text-size {
  display: block;
  text-align: right;
  padding-top: 10px;
  color: blue !important;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-role="page" id="p1">
  <div data-role="content">
    <ul data-role="listview" data-inset="true">
      <li data-role="list-divider">Item Title</li>
      <li>
        <div class="less">
          Need to detect if this text is long enough to show the "Read More" if it is not don't
        </div>
        <div class="text-size">Read more...</div>
      </li>
    </ul>
  </div>

</div>

Is it possible to detect if the text is short enough to fit within the div and then hide the read more option?

like image 423
Donal Rafferty Avatar asked May 19 '14 17:05

Donal Rafferty


2 Answers

You can compare DIV width with scrollWidth to detect if text is overflowing:

if ($('.less')[0].scrollWidth <= $('.less').width()) {
   $(".text-size").hide();
}

Demo: http://jsfiddle.net/ygalanter/M2APS/50/

like image 119
Yuriy Galanter Avatar answered Oct 19 '22 05:10

Yuriy Galanter


There is a jQuery plugin that may suit your needs: http://jedfoster.com/Readmore.js/

like image 44
eat-sleep-code Avatar answered Oct 19 '22 05:10

eat-sleep-code