Fyl
Fyl

Reputation: 288

Truncate text and restore it as needed

My Codepen

if("matchMedia" in window) {
    if(window.matchMedia("(max-width: 533px)").matches) {
      $('.title').each(function() {
        var theContent = $(this).text();
        if (theContent.length >= 35) {
          var n = theContent.substring(0, 35);
          $(this).html(n + '...');
        }
      });
    } else {
      // ??
    }
 }

Hello,

I have to create a function that must make sure to truncate text too large when I pass on a mobile resolution. The first part (truncation) works, but I can not finish it to restore all the titles on my page when the resolution goes above 533px.

Can someone give me a track? Or give me a better method to do if there is better?

Thank you very much.

Upvotes: 0

Views: 138

Answers (2)

epascarello
epascarello

Reputation: 207501

I would highly recommend that you do it with purely css, but if you really need to do it, you can use attributes or data attribute to hold the original text.

$("#test").on("change", function() {

  if (this.checked) {

    $('.title').text(function(i, orgText) {
      var elem = $(this);
      if (!elem.data("orgText")) {
        elem.data("orgText", orgText);
      }
      return (orgText.length >= 35) ? orgText.substring(0, 35) + "…" : orgText;
    });

  } else {

    $('.title').text(function(i, text) {
      return $(this).data("orgText") || text;
    });

  }


}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 class="title">12345678901234567890123456789012345678901234567890</h3>
<h3 class="title">1234567890123456789012345678901234567890</h3>
<h3 class="title">1234567890</h3>

<input type="checkbox" id="test" checked>
<label for="test">shrink</label>

Upvotes: 0

Schlaus
Schlaus

Reputation: 19212

How about pure CSS?

.title {
  width: 50%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
<div class="title">
  I am a somewhat long title, that will not fit on all screens
</div>

Upvotes: 2

Related Questions