Question

I am trying to cut down the visible length of a string to about 25 characters. I want to keep the whole string on the page. Hidden of course.

<span>This message is 34 characters long</span>

$("span").text(function(index, text) {
    return text.substr(0, 25);
});

Will return

This message is 34 charac

Where I want it to write This message is 34 charac but keep the rest of the characters hidden, so I can display them later using .show() or something else.

Was it helpful?

Solution

Store it in jQuery's data()

$("span").text(function(index, text) {
    $(this).data('txt', text);
    return text.substr(0, 25);
});

Later you can just do

$("span").text(function() {
    return $(this).data('txt');
});

OTHER TIPS

You could write the whole string to a html element of it's own that has a style of display: none. You could also add a data attribute to the span tag as well.

$("span").html(function(index, text) {
    return text.substr(0,25) + '<span style="display:none">' + text.substr(25) +'</span>';
});

Add the string to a data attribute:

<span data-text="This message is 34 characters long"></span>

$("span").text(function(index, text) {
  return $(this).data('text').substr(0, 25);
});

Demo

You can use a CSS property: Select the div where you save the string like this

  <div>My String</div>
  <style>
  div{
     width: 50px;
     overflow: hidden;/* this will hide all the content that surpass the width */
  }
  </style>

I would wrap the unwanted part in a hidden span, so I could use .toggle() on it after.

$('span').html(function(index, oldHtml) {
        return oldHtml.substring(0,25) + '<span class="toggleHidden">' + text.substr(25) + '</span>';
});

$('.toggleHidden').toggle();

Note the use of .html() instead of .text() as the first one allows me to set HTML elements as children.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top