JQuery read more. Hide and deposit excess text - jQuery plugin

The task is quite standard, however, the search for a suitable jQuery plugin was not crowned with success, since in all the plugins that managed to find, the constraints are specified not by the number of characters, but the height of the block. That is, the height of the container is indicated, and the plugin cuts the text going beyond its limits. On the Internet you can find very convenient options for such plugins, for example, readmore.js and dotdotdot. Moreover, the latter can even track the change in the window size and automatically update the result.

However, the problem was that the adaptive site and the block takes different widths depending on the width of the browser window. As a result, the situation could have happened when very few characters would be in the block. Of course, it is possible to change the height of the block at some algorithm to the window, however, it was decided not to do some kind of superstructure over some finished solution, and write your small plugin that will trigger text on jQuery based on the specified number Symbols.

You can highlight a few advantages of this approach.

  1. You can be sure that the text will be displayed in the block, which bears the semantic load even in the rolled state.
  2. Unfinished handlers for changing the window size, which would constantly check how many text closes in the block.

When implementing, it was also necessary to take into account two things affecting the beauty of the result. First, it is necessary that the text cut into the whole word. Secondly, avoiding the situation "disclose too little" - can occur in the case when the total number of characters in the block slightly more than the specified value in which cropping, for example, is 50-100 characters. If the parameters are not specified, the module will use default values.

So, the task algorithm is quite simple:

The most time-consuming part of the implementation of the HTML-spoiler script is obtaining an announcement of the full text of the unit, since the block may not be simply text, but a markup formatted using HTML tags.

Below is a function that is responsible for cutting out the HTML-code of a piece, in which the number of characters that are not HTML-markup equally set in the parameters value or more by the end of the end of the announcement of the announcement.

// formation of the announcement of person.cutbrief \u003d function () (var tmp, i \u003d 0, // Cycle meter j \u003d 0, // HTML cycle counter \u003d data.html, // HTML block HTMLLENGTH \u003d HTML.LENGTH, // Number HTML Count \u003d 0, // Text Character Counter COUNTFLAG \u003d TRUE, // The current symbol is not an HTML markup ENDCHARSLEN \u003d ENDCHARS.LENGTH, // Size of array of characters indicating the end of the word END \u003d HTMLLENGTH, // Position of the end of the announcement When searching resultlimit \u003d data.limit.total - data.limit.delta, // Required number of characters tagname, // Tag name TagStack \u003d; // Tag stack you want to close at the end of Announcement if (data.count\u003e data.limit .total) (// Form the Announcement for (; I< htmlLength; i++) { // если открывается тег if (html[i] === "<") { countFlag = false; // символ не последний if (i < htmlLength - 1) { // тег является закрывающим if (html === "/") { tmp = html.indexOf(">", I + 1); if (TMP\u003e 0) (// The right closing format tagname \u003d html.substr (i + 2, TMP-i-2); // The detected tag should have a closing part? if ($. Inarray (Tagname, Tagdic)\u003e \u003d 0) (tagstack.pop ();))) Else (// Tag is opening // The following symbol is any Latin letter? if (/\\w/gi.test_html)) ( // Receive the tag name and define it on the need to close TMP \u003d HTML.INDEXOF ("\u003e", i + 1); if (tmp\u003e 0) (tagname \u003d html.substr (I + 1, TMP-i-1); // The tag must have a closing part if ($ .inarray (TagName, Tagdic)\u003e \u003d 0) (tagstack.push (tagname);)) ELSE (// is not Countflag \u003d True;)) Else (// is not Tag Countflag \u003d True;)))) // Incrementim text symbol meter IF (Countflag) (Count ++;) // If the IF tag is closed (HTML [i] \u003d\u003d\u003d "\u003e") (Countflag \u003d True) // Reached Up to the end of the required size of Announcement if (count\u003e \u003d resultlimit) (// The current symbol is not the end of the word if ($ .inarray (HTML [I], ENDCHARS)< 0) { // символ не последний if (i < htmlLength - 1) { // следующий символ тоже не конец слова if ($.inArray(html, ENDCHARS) < 0) { // ищем первое вхождение каждого символа из набора и выбираем ближайший for (; j < endCharsLen; j++) { tmp = html.indexOf(ENDCHARS[j], i+1); if ((tmp > 0) && (TMP< end)) { end = tmp; } }; i = end; } } } else { // слово закончилось целиком count--; } break; } }; // вырезаем кусок html data.brief = html.substr(0, i); // добавляем точки data.brief += opt.ellipsis; // закрываем открытые теги for (i = tagStack.length - 1; i >\u003d 0; I--) (Data.Brief + \u003d "";);) ELSE (// Do not cut the data.brief \u003d html;));

Applied plugin standard:

$ (". b-block - first"). Readmore ();

The plugin provides the following parameters:

  • ellipsis (String) - Symbols that will be output at the end of the announcement;
  • textOpen (String) - Link text in a rolled state;
  • textClose (String) - Link text in the expanded state;
  • callback is a function that is performed after the disclosure / closing of the unit;
  • brief (Integer) - the maximum number of announces symbols, reduced by the value of the Addition;
  • aDDITION (Integer) is the minimum number of characters of the disclosed part of the text;
  • smoothly (Integer) - the time of smooth disclosure / closing of the block in milliseconds.

It should be noted that the Callback function works only after the end of the animation of the text, which is performed on jQuery using the Animate method, and receives two input parameters: Block link and current state.

Below is an example of how it is possible depending on the state of the block, perform any of your actions:

$ (". b-block - second"). Readmore ((Ellipsis: "[...], TextPen:" Open ", TextClose:" Close ", Callback: Function (Self, State) (State? Self .css ("Background", "# E74C3C"): Self.css ("Background", "# 3498DB");), brief: 500, addition: 100));

CSS In the example at a minimum, it is possible to do without it at all (code is shown on SCSS):

B-Readmore (Padding: 15px 0 0 0; & __ link (Color: # 000; Text-Decoration: Underline; &: Hover, &: Focus, &: Active (Color: # 000; text-decoration: none;)) & __ Open (Display: Inline-block;) & __ Close (Display: None;) & - Opened & (& __ Open (Display: Inline-Block;)))

We appreciate and comment on how to better make a spoiler for the site according to the number of characters.

Plugins from this selection are not for the creation of phintips and various beautifulness, for example, animation or the like, and to ensure correct web page. They will be needed in the case when it becomes powerless before the task. For example, fir need automate text trimming by characters or block heightif you need quickly and right set up a typography in an adaptive site, as well as when wisdom leveling text etc.

We in our work very often use or used these plugins before. So. For your attention 10 best jQuery plugins to work with textthat will help to quickly and effectively implement a non-standard designer idea.

TextTailor - trimming text depending on the height of the block

TextTailor is a very useful plugin that will help trim text (Put the Cut or link "More details") so that it fill the container as much as possible in which it is located. That is, it allows crop text depending on the height of the parent block And remove everything that did not fit under the cat. The only condition for the correct operation of the script is the presence of a block of a given height in a fixed or percentage value.
TextTailor is often used on pages with a list of articles in the form of a tile when blocks with preview of the tops are located several pieces in a row and at the same time the titles of articles of different volumes. It may further complicate if the width of these blocks changes, for example, in. In such cases, as a rule, the number of brief description characters (annotations) is roughly limited, and due to the fact that the headers have different heights, empty areas are obtained in blocks. TextTailor will help bypass this problem and fill the message block text.

P / S. Perhaps someone will be useful. Once we published a plugin called flexmenu.which regulates the number of items depending on the width of the parent block. All that is not placed is sent to the drop-down list. He was with an article titled "5 adaptive menu for different tasks."

In addition to all this, the plugin performs the second, no less important function. With it, you can scaling the multi-line text depending on the size of the parent block or screen. All you need to do is configure the required parameters, the rest of the plugin will do for you. It will automatically change the box and font size relative to the screen size User to ensure the most comfortable reading.

Succinct - trimming text by the number of characters

Succinct - jQuery plugin that allows you to put a link "More details" or a dot after a specified number of characters in the text. All that did not fit - cuts off.
In essence, this is a standard approach in trimming text, only with jQuery tools, and not on PHP.

Readmore.js - hide text under the spoiler

Readmore.js allows hide part of the text under the spoiler. The script, after a specified number of characters in the text sets the "More details" button, when you click on which a hidden part of the text appears with the "Departure" effect, shifting the rest of the content.

FitText - text scaling on screen width

FitText - Jqery Plugin, which dynamically changes the font size depending on the screen width or parent block. It is perfect for creating screens headers in adaptive sites. Now you will not need to change the font size for each screen resolution.

Auto Line-Height - Automatic Rate Distance

AUTO LINE-HEIGHT allows automatically calculate Lineheight (string height) when changing the size of the window. As a rule, applies in adaptive sites to improve the readability of text on mobile devices.

Bacon - text alignment by curve

Bacon is a jQuery plugin that will help align text on a page for a given circumference or curve.
This decision is used in work infrequently, but in the wisdom designer idea it is not without it.

jqslickwrap - text alignment in the image

jQSlickWrap allows you to align the text as you are pleased. Often used for aligning text on some subject is depicted in the picture. That is, not according to the specified sizes itself, namely, what is depicted in the photo. The screenshot is well shown the principle of his work.

Good day!

Start from the very beginning, in the case, if someone does not know anything at all.

I was not at sea.

- Okay, do not fill, never was at sea!

- I did not happen ...

- already knocked on heaven, pumped up Telemy, literally spent themselves on the last journey, and you did not attend the sea?!

- I did not have time, did not happen ...

- I did not know that in heaven nowhere without this?

k / f "Reach to heaven"

How to add more

So, what fragment of the text to display in the announcement is set using the tag more. This tag shares an article into two parts: an introductory (announcement) and continued.

In the WordPress editor, the more can be inserted with the button in the toolbar.

1. Visual editor mode:

2. Text mode editor:

In text mode, you can also manually split the record: Just write

And now important information that is not all knowing!

So, there is an elementary way to set every link after the announcement of your unique text!

You can do it, just writing, the desired text inside the design with more. Like this:

Ask why to do so? Still prescribe text every time.

Honestly, such a thing \u003d) already published 84 articles, and only "resumed" about this.

How to change text?

1. The first is the easiest way to add your text (usually in index.php) to The_Content function

2. Second way using hook The_Content_more_Link.. Just add the following code in and specify the desired link text.

function My_more_Link ($ More_Link, $ More_Link_Text) (RETURN STR_REPLACE ($ more_link_text, "continue reading ...", $ more_link);) Add_filter ("The_Content_More_Link", "My_more_Link", 10, 2);

This method is convenient what you do not need to search for the template files, where you are using the_content (this is not necessarily in index.php, maybe content.php and anything.) Here you only work in the FunctionS.php file.

3. In the third paragraph, simply saving a method for history using an arbitrary WordPress field.

ID, "Custom_more_Text", True); if (! $ Custom_More) ($ Custom_more \u003d "Continue reading an article" ";) The_Content ($ Custom_More); ?\u003e

Fitting text directly inOf course it's easier and clearer.

Here just adjust the function call the_Content One of two ways.

How to remove #more from the link

In the code, this anchor is installed in this way: