GithubHelp home page GithubHelp logo

kswedberg / jquery-expander Goto Github PK

View Code? Open in Web Editor NEW
460.0 28.0 168.0 700 KB

Expand and Collapse HTML content

Home Page: https://kswedberg.github.io/jquery-expander/

License: Other

JavaScript 94.28% HTML 5.72%

jquery-expander's Introduction

Overview

The Expander Plugin hides (collapses) a portion of an element's content and adds a "read more" link so that the text can be viewed by the user if he or she wishes. By default, the expanded content is followed by a "read less" link that the user can click to re-collapse it. Expanded content can also be re-collapsed after a specified period of time. The plugin consists of a single method, .expander(), with a bunch of options.

Features

  • works for inline and block elements (as of 1.0)
  • optional word counting of detail text
  • configurable class names and "more", "less", and "word count" text
  • configurable expanding effect
  • callbacks for all states: on initial slicing of the content, before content expands, after content expands, after content collapses
  • manual override: if content is smaller than slicePoint but contains an element with the detail class, the content will be sliced just before the detail element and act the same way as elements that meet the slicePoint and widow criteria.

Options

The following options, shown here with their default values, are currently available:

// the number of characters at which the contents will be sliced into two parts.
slicePoint: 100,

// a string of characters at which to slice the contents into two parts,
// but only if the string appears before slicePoint
// Useful for slicing at the first line break, e.g. {sliceOn: '<br'}
sliceOn: null,

// whether to keep the last word of the summary whole (true) or let it slice in the middle of a word (false)
preserveWords: true,

// whether to normalize the whitespace in the data to display (true) or not (false)
normalizeWhitespace: true,

// whether to count and display the number of words inside the collapsed text
// This will either allow or prevent the word count
// (and thus the configurable wordCountText) from showing.
showWordCount: false,

// text to include between summary and detail. Default ' ' prevents appearance of
// collapsing two words into one.
// Was hard-coded in script; now exposed as an option to fix issue #106.
detailPrefix: ' ',

// what to display around the counted number of words, set to '{{count}}' to show only the number
wordCountText: ' ({{count}} words)',

// a threshold of sorts for whether to initially hide/collapse part of the element's contents.
// If after slicing the contents in two there are fewer words in the second part than
// the value set by widow, we won't bother hiding/collapsing anything.
widow: 4,

// text displayed in a link instead of the hidden part of the element.
// clicking this will expand/show the hidden/collapsed text
expandText: 'read more',
expandPrefix: '&hellip; ',

// class names for summary element and detail element
summaryClass: 'summary',
detailClass: 'details',

// one or more space-separated class names for <span> around
// "read-more" link and "read-less" link
moreClass: 'read-more',
lessClass: 'read-less',

// number of milliseconds after text has been expanded at which to collapse the text again.
// when 0, no auto-collapsing
collapseTimer: 0,

// effects for expanding and collapsing
expandEffect: 'slideDown',
expandSpeed: 250,
collapseEffect: 'slideUp',
collapseSpeed: 200,

// start with the details expanded (and the "read-less" link showing)
startExpanded: true,

// allow the user to re-collapse the expanded text.
userCollapse: true,

// text to use for the link to re-collapse the text
userCollapseText: 'read less',
userCollapsePrefix: ' ',


// all callback functions have the this keyword mapped to the element in the jQuery set when .expander() is called

onSlice: null, // function() {},
beforeExpand: null, // function() {},
afterExpand: null, // function() {},
onCollapse: null // function(byUser) {},
afterCollapse: null // function() {}

Known Issues

  • If you use the default 'slideDown' for the expandEffect option, the detail element's style will always get either display: block or display: inline-block when expanded. These display properties, in turn, will start the detail text on a new line, which might not be what you expect. You can usually avoid this problem by setting the expandEffect option to 'fadeIn' instead.
  • A couple people have reported (in issue #24) that if you use 'fadeIn' and 'fadeOut' for the expandEffect and collapseEffect options, the plugin appears to cause IE9 (and possibly older IEs) to crash after repeatedly expanding and collapsing some text. Since the plugin itself doesn't do much when expanding/collapsing, my hunch (confirmed by one of the reporters) is that the crash has to do with animating the opacity of elements. I haven't been able to reproduce the problem on my machine, which leads me to believe that certain graphics settings in Windows must also be contributing to the bug. In any case, if this is a concern for you, avoid using fades for those effects options.

Workarounds for inherent issues

  • For ideographic scripts, such as Chinese, the following options should be applied:

    {
      preserveWords: false,
      widow: 0
    }
  • It is not possible to change the text inside an element that has had expander already applied to it, because elements are already split up into detail and summary texts. Almost everything that happens during initialization in expander needs to be repeated on a change in content to properly display the altered content. To do this, expander first needs to be destroyed, then reinitialized on the content (with settings).

    $('#my-element')
    .expander('destroy')
    .html('<p>The HTML you want to replace the current html with goes here</p>')
    .expander({
      showWordCount: true,
      preserveWords: false,
      slicePoint: 30
    });
  • As noted by a number of people (issues #56, #60) this plugin can cause "flickering" in its expandable elements on loading the webpage. It usually happens when multiple other scripts are present and the expander stalls during its initialization. It is (sadly) an issue that stems directly from its method of making expandable text, and cannot be fixed without changing what the plugin is, or how it operates. Nonetheless, the flicker can be prevented by the same semi-hacky fixes normally used for other FOUC (flash of unstyled content) issues:

  1. Add a JS script in the head that will add a "js" class to the html element (see http://www.learningjquery.com/2008/10/1-way-to-avoid-the-flash-of-unstyled-content/). This is done by JavaScript so that the element will not be hidden for clients with their JavaScript disabled/inoperable.

  2. Add the following somewhere in your CSS (using your own class names):

    .js .myexpander.js-myexpander-hidden {
      display: none;
    }
  3. Add a JS script that will execute later (bottom of body or within $(document).ready()):

    $('.myexpander').expander().removeClass('js-myexpander-hidden');

    a. If you still see a little "flash" of unstyled content, add this script to remove the class in an onSlice callback:

    $(.myexpander).expander({
      onSlice: function() {
        $(this).removeClass('js-myexpander-hidden');
      }
    });

Injecting with CommonJS or AMD

// CommonJS
var jQuery = require('jquery');
require('jquery-expander')(jQuery);

// AMD
define(['jquery', 'jquery-expander'], function (jQuery, expander) {
  expander(jQuery)
})

Demo

A demo is provided in the repo's demo directory. Feel free to take the plugin for a spin at kswedberg.github.io/jquery-expander/demo/

Tests

The Expander Plugin comes with a set of unit tests to ensure that it is working as expected. You can run these tests online at kswedberg.github.io/jquery-expander/test/ or locally from the repo's test directory.

License

This plugin is free of charge and licensed under the MIT license.

jquery-expander's People

Contributors

dependabot[bot] avatar fourteenmeister avatar jbruni avatar jeancarriere avatar kswedberg avatar mariano avatar math2k avatar mkormendy avatar samlii avatar sebtools avatar taskinoz avatar teo1978 avatar terrabruder avatar travco avatar treyhunner avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery-expander's Issues

specify width

If I specify the width of a element to wrap, the 'more text' will display on a new line :( Anyone known with this issue?

page already expanded

Hello, Great plugin, I am new to github so please apologies if I am doing this wrong.

I used the plugin inside a div but the problem is the page seems to be filled with whitespace (that would fit the text hidden) below the read more button.

How do i remove this whitespace? It seems to create the page with the text showing, and then hide it, that is the length of the space.

Many thanks,

Bob

Slicepoint not being recognized.

No matter what value I put in the slicepoint, it always cuts of at 98 characters.
The html is this:

I love to travel with my husband and kids and always do thorough research of the place to go because we have a big family and lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ac sapien vel dolor rutrum egestas hendrerit at ipsum. We got a winner, I said we got a winner, we got a winner! Our next winner is that delightful personality, straight from Brighton beach Brooklyn, Please give a juicy welcome to Mrs. Sarah Goldfarb! The Audience: Juice by Sarah, juice by Sarah, juice by Sarah oh, Sarah's got juice, Sarah's got juice, ohhhhhhhh Sarah. I'm somebody now, Harry. Everybody likes me.



the javascript is
$('div.mottoHolder2 p').expander({
slicepoint: 200,
expandText: "View more",
userCollapseText: "View less"
});
The truncated text is
I love to travel with my husband and kids and always do thorough research of the place to go … View more

---No matter what I change the slicepoint value to, it always truncates to this amount. I'm using the minified version you posted yesterday.

table break problem

when its break in table portion, read more button appears top of table.
another issue will be helpful if there are a options to break tag by tag.

Is 'destroy' supposed to re-expand compacted elements?

Hi,

First thanks for this plugin, it's pretty nifty and I'm pretty close to getting what I need out of it. I'm working on an outline mode that crunches long articles into shorter versions. This is triggered by the user clicking on a button, an action that the user should then be able to roll back by clicking the same button again. This is shown in simplified fashion in the following jsfiddle example using a link called "[OUTLINE]".

http://jsfiddle.net/2wUJG/

Applying expander('destroy') does remove the expanding links [+], but it does not show the full content (unless the element had manually been expanded beforehand), which was my expectation. In other words my code is intended to re-expand all the elements that had been compacted. Maybe there's something wrong with my selectors?

Thanks for any help.

PS: destroy is not documented at http://plugins.learningjquery.com/expander/index.html#options

I had to Google to find the Github ticket which introduced that ability to the expander method.

Re-running expander doesn't work without calling expander('destroy') first. Maybe add an auto-destory option?

Hey Kswedberg, thanks for the great expander.

I was using it with a dynamically changing block of text and I ran into the problem that it doesn't work to reapply expander.

I have resolved it by using destroy:

$('#mydiv').expander('destroy').expander();

But it seems to me that since re-calling expander on an already 'expandered' object doesn't seem to do anything, you could make it the default that it calls destroy first?

I'm not sure what the ramifications of that would be. Alternatively, you could autodestroy on update listener functionality that destroys and reapplies expander whenever the html of an expander is changed?

In any event, at least it could be documented somewhere to use the expander('destroy') if that is a legitimate use case.

I've got a very straightforward example here:

http://jsfiddle.net/6dW6U/74/

showing both expanded text and collapsed text in asp.net ajax accordian control

Showing both the expanded text and the collapsed text on first load. When collapsed then it works as expected. Tried text raw in div and in label, same results. Using an accordian control.

litora torquent per conubia nostra, per inceptos himenaeos. Proin rhoncus, elit laoreet fermentum convallis, turpis enim porta tellus, a feugiat lorem mi rhoncus elit. Nulla lacus diam, bibendum ac [ … read more] tempus at, tincidunt vitae risus. Sed diam mi, vulputate sed congue et, euismod eu ante. Mauris dapibus, sapien a imperdiet aliquet, turpis quam auctor tortor, ut rutrum urna enim ac ante. Praesent dapibus imperdiet accumsan. Ut mollis sagittis nisi, eu cursus elit malesuada id. Cras sollicitudin vehicula libero. Nam nec nisl sapien. Fusce odio lacus, tempor eget vulputate in, pulvinar sed arcu. Nulla ipsum erat, varius id posuere a, luctus at eros. Aliquam vestibulum faucibus tempus. Aliquam lobortis ante vitae erat sodales id eleifend quam placerat. Phasellus hendrerit turpis ligula. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Quisque arcu nisl, venenatis sed interdum mollis, vestibulum et odio. Ut commodo sapien a justo pharetra mattis. Curabitur feugiat ultricies gravida. Vestibulum varius consectetur urna, non vehicula mi tristique nec. Cras facilisis tincidunt justo sed auctor. Morbi mi est. [^]

slicePoint did not effect to other unicode characters but only english.

<div class="expandable">
<p>
这首歌的名字是《大家好我叫小莫》;私はあなたのために何ができるか教えてください?这首歌的名字是《大家好我叫小莫》;私はあなたのために何ができるか教えてください?这首歌的名字是《大家好我叫小莫》;私はあなたのために何ができるか教えてください?这首歌的名字是《大家好我叫小莫》;私はあなたのために何ができるか教えてください?
</p>
</div>
$(document).ready ()->
  expander_opts =
    slicePoint: 30
    expandPrefix: " "
    expandText: "..."
    userCollapseText: "[^]"
  $('div.expandable p').expander expander_opts

while it doest works.

Expander does not break long strings

This is an edge case, but if the user inputs a long string, the expander does not break the string at the specified slice point. For instance, if you create a string of W's that is 300 characters long and then you set the slice point to 250 on that string, it does not slice it.

Is there a way to fix this edge case so that it breaks the string like normal? Thanks for your help!

flickering

Hi,

first of all great job on this jquery plugin it's easy to use and does a magnificent job.
However i have noticed that the plugin flickers the text you want to expand
when i try to expand a div before sliding down is there any workaround for this without getting your text to slightly flicker and still see a smooth slidedown?

i have noticed example 3 on the site also has this kind off flickering when you expand it
http://plugins.learningjquery.com/expander/demo/index.html

Problem with checkbox state when checkboxes are in the expanded div.

Hi.

We are building an ASP.NET application that has a list of checkboxes inside of a div. We are trying to use the expander on the div element so the user only sees some of the checkboxes but can click 'more' to see the rest.

The expander is allowing us to click on the more/less and that works fine, however, when a person unchecks a checkbox, the checkbox value is not sent back properly on the submit (it always comes back as checked). We've verified this with Fiddler. If I comment out the line with expander(), all works fine with the checkboxes.

After some experimentation, we've also noticed that this behavior only occurs on 'always visible' checkboxes. If I check/uncheck a checkbox that is hidden by the more/less, that correct value is posted back.

I've verified this with Chrome and IE9. Have you seen anything like this? Can the expander be used with form controls like checkboxes and text boxes?

Thanks!
Brian

ö, ä, ü, ß break summary

If you have some special characters in the mix words are split appart even when you turn on preserveWords: true

This is confirmed for the German Umlaute ö ä ü ß but might also be the case for some other characters (e.g. é û etc.)

Doesn't split as neatly with p elements

This script works really well when you use breaks for entering but when you use paragraphs it gets a bit ugly at the split point. since its closing the paragraph and reopens it after the split. Could you make it to close the paragraph when closed but reopen it without putting one in between when opening it?

UL break problem

The expander works nicely if I run it with plain text.

My problem arises when I try to show other elements inside the (expander) p tag such as a ul list.
A p tag can not contain lists and automatically closes the p tag before the ul tag.
So the list ends up outside the p tag and is therefore shown constantly.
Example:

I december skulle Finansdepartementet ha presenterat sitt förslag på en ny miljöbilsdefinition, som ska börja gälla frå… Read more

-Har den nya politiska ledningen i Miljödepartementet något att göra med att de nya miljöbilsreglerna och principerna för supermiljöbilspremien dröjer?
-Var den nya politiska staben på Miljödepartementet inte nöjd med den tidigare inriktningen?
-Vilken inriktning har det nuvarande arbetet?

The read more part for the first paragraf still works...

Is there a way around this problem?

Chrome Not Word Wrapping

The Google Chrome browser doesn't like something that's going on with this plugin. Your demo page shows this behavior clearly on the very first item... What happens is the paragraph doesn't word-wrap once you expand it so the text all goes off the screen.

The variation I started with was: expander was applied to the parent div of many p tags. Each p tag introduced a line-break but no paragraphs wrapped. Explicitly setting the width on the paragraph in the CSS also failed to get Chrome to wordwrap.

Thank you for this plugin. It's excellent. I'm using the most recent version (9/16).

//

slicePoint option not working

Hi, When I try to set the option slicePoice to something other than the default, it doesn't work and cuts off at the default 100chars, here's my JS:

    <script type="text/javascript">
            $(document).ready(function() {
            $('dl.expander dd:eq(0)').expander();
            $('dl.expander dd:gt(0)').expander({
            preserveWords: true,
            slicePoint: 200,
            collapseTimer: 0,
            userCollapse: true,
            beforeExpand: function() {
              $(this).parent().parent().append('<div class="success">before expand.</div>');
            },
            afterExpand: function() {
              $(this).parent().parent().append('<div class="success">after expand.</div>');
            },
            onCollapse: function(byUser) {
              var by = byUser ? 'user' : 'timer';
              $(this).parent().parent().append('<div class="success">on collapse (' + by + ').</div>');
            }
          });
        });
    </script>

Thanks.

Conflicts with another script

Hi,

First I want to thank you, I love this plugin! However, it conflicts with another script I have running on my page. I am running this reftagger: http://www.logos.com/reftagger.

I know so little about how to write any scripting and am only starting to be able to comprehend reading it, so I cannot understand why it conflicts. Any ideas?

Thank you!

Mobile - shows all text before collapsing

Great plugin, thanks!

I've notice on mobile (iOS and Droid) that the full text shows for a split second, then it collapses to "see more". Is there a way to avoid this?

Thanks,
-mm

Slice point in pixels

Hi,

I have been using your plugin for a while, and it's really great!

One thing though, it's too bad we can't set the slice point in pixels, like to define which height of a div has to be showed/hidden.

I think it would be really useful in some cases...

Not sure I should post this here, but I didn't find a feature request on the site...

Expander on live elements as well as divs

I guess this isn't really an issue, but I bet it is a common headache for some people.

  1. I have a few divs generated via ajax. How can I apply expander on them?
  2. Several divs are placed inside of a wrapper div, how can I specify the slicePoint to the number of divs or elements instead of characters or words?

Thanks.

Inline Style

The expander seems to break if you have html inline style. No matter where I split the text it does not work.

Calling .expander() on dynamic text

I have a paragraph in which I am replacing the html contents, but calling expander on it does not work.

<p id="target">I'm a placeholder.</p>

<div id="data">
    <p data-id="123">I'm the new, ultra long text that really needs to be collapsed.</p>
</div>

vid_id = 123;
$('#target').html($('#data p[data-id="'+vid_id+'"]').html()).expander();`

How can I solve this issue?

moreClass / lessClass not applying

Hi,
Thanks for the plugin, it's great!
I have an issue though, I have applied classes to the span around 'read more' link, but they aren't getting applied to the actual span. Here's how I did it:
jQuery('.excerpt').expander({
slicePoint: 400,
expandText: 'Read more',
userCollapseText: 'Read More',
preserveWords: true,
expandEffect: 'fadeIn',
expandSpeed: 400,
moreClass: 'review-readmore',
lessClass: 'review-readmore'
});

Any ideas what's wrong here?
Thanks for any help in advance!

  • Rutwick

Ignore tags

An option to ignore tags in the text would be very useful.

Spacing missing after expanding

When expanding the space between summary and detail text disappears. For example:

Add some
becomes
Add somemore content
instead of
Add some more content

Have made a work around by adding a non-breaking space into the following code:

// otherwise, continue...
lastCloseTag = closeTagsForsummaryText.pop() || '';
summaryText += closeTagsForsummaryText.join('');
//detailText = openTagsForDetails.join('') + detailText;
detailText = openTagsForDetails.join('') + ' ' + detailText; //fixed this line

It works but leaves two spaces which is better than none but one would be better still :)

Update to this. Forgot to say this only happens in auto mode. When you insert the read more and less links by hand it all works as expected.

Conflict with Fancybox?

Hi!

Thanks for a great script!

I'm experiencing some problems running it together with fancybox though.
I've isolated the problem so I know there is something in the expander plugin that conflicts with fancybox.

The problem I'm having is that when I make a gallery with fancybox, images are showing up as doubles.
Look at example two with an image gallery and next/prev buttons to view images here:
http://fancyapps.com/fancybox/

To enable fancybox you add the class fancybox to an image link and to make it a gallery you add a rel="fancybox" to every link that you want the gallery to include (as example two shows).
The problem is when I also have the expander plugin active the same image shows up twice when I click the fancybox next/prev buttons. If I remove the expander script it works as supposed, no doubles.

Any suggestions for this?

Thanks again for the plugin!

expand effect is ignored

Great plugin! It seems to be one of a kind, which is why I'm hoping to fix this issue instead of writing something else from scratch.

Tested in Firefox and Chrome on Mac and I get the same issue: expandEffect: 'slideDown' simply doesn't work.

First off, I had to remove a paragraph element and replace it with a div. The paragraph element flickered pretty badly on collapse and expand in both browsers, right at the begging of the expand and the end of the collapse.

Here are my options. The collapse works great at any speed I provide. The expand just snaps into place abruptly. I'm researching if this is a quirk with jquery slideDown or not, the doc has a comment saying slideDown won't work if the element has a min-height set but that's not the case.

$('.media_meta dl dd.release_text div').expander({
    collapseEffect: 'slideUp',
    collapseSpeed: 500,
    expandEffect: 'slideDown',
    expandSpeed: 500,
    expandText: 'more',
    slicePoint: 300,
    userCollapseText: 'less',
    widow: 2
});

Option to shorten by element height

It would be nice if there was an option to shorten according to the element's height (or number of rows).

I want to shorten user comments which are lists like

  1. Foo
  2. Bar
  3. Baz
    ...
  4. Etc.

They don't use much text but much height.

Would be cool to shorten text if the element is higher than defined OR has more characters than slicePoint.

Destroy method not working correctly

The destroy method does not work correctly as the following bit of code " !this.data('expander') is always undefined " which means the method returns.
if ( !this.data('expander') ) {
return;
}

My expander is set using the following.

$(document).ready(function() { // override default options (also overrides global overrides) $('#editable-inline-bodyhtml').expander({ slicePoint: 120, expandPrefix: '... ', expandText: 'View More', // default is 'read more' userCollapseText: 'View Less' // default is 'read less' }); });

I added the following piece of code to correct this

$.data(this, 'expander', o);

I can do pull request if you like just not sure how to update the tests

Can't apply to same element twice.

My scenario is this: Have a block of copy that gets collapsed on load. User can edit this text live... say they've added 10 paragraphs... Once they save the new copy and it gets put back into the DOM... I want to be able to reapply or reinit the plugin to collapse the new text. However, it does nothing :/

Essentially, I need to be able to init the plugin on the same element and have it update. If i init it once, then try to do it again, with say a different slicepoint, nothing happens.

Thanks for your hard work on this plugin.

collapseEffect, collapseSpeed ?

Hi,
This is a missing feature I may say...
There is an option to add an 'expandEffect', but no option to add a 'collapseEffect'... Please could you add it?
It looks really weird when the div closes quickly, a simple fadeOut /slideUp would make the effect look complete and cooler !

I would like to hear more on this!

Thanks,
Rutwick

Preventing a FOUC

How do I prevent a FOUC (flash of unstyled content) on an element which is modified by the plugin?

A div has lots of text, which is "compacted" by the plugin. But before the plugin executes, the full div is shown, and then the user can see it being compacted.

So I added a "max-height" to the div, and then removed it after, but that doesn't work well.

What is the best approach for this sort of problem?

expand limited to <p> ?

By default this plugin collapses text that appears within <p> and </p> tags. You get a separate expandable block for each paragraph. What happens if I want to collapse a large piece of text, containing several paragraphs all into one single expandable block however?

Close expanded text by clicking something else

I don't like putting this under "Issues," but not sure where else it should go. I have a situation that has me showing various collapsed blocks in different locations on the screen (sometimes even off screen). I would like to know if there is a way, or ask for the functionality, to collapse anything that is expanded, based on any event.

So if a user clicks something, hovers over something, etc, I can call the collapse method to ensure all expanded blocks are collapsed.

nested tags interrupt the sumTagLess counter

I recently implemented this plugin (version 1.4.5) , as follows:

// slicePoint: 235
<div class="expandable">
  <p>
    Can your students apply Gibbs Free Energy equation? Gain insight into your</p>
  <ul>
    <li>
      <u><em><strong>students' prior knowledge and</strong></em></u></li>
    <li>
      <u><em><strong>misunderstandings of Building Block A to help you select</strong></em></u></li>
    <li>
      <u><em><strong>activities that build their ability to make predictions about changes in free energy availability at the molecular and cellular level.</strong></em></u></li>
  </ul>
</div>

With this example, I discovered that the first nested opening tag without a space in front of it (<em>) is treated as a text character in the while (summTagless < o.slicePoint) loop and the rest of the summary text counting is then thrown off. This really showed up in differences between FFX and IE8 because of additional markup attributes in IE8 which were being treated as text.

It seemed to fix the problem when I updated the rTagPlus regex to account for nested tags:

OLD: rTagPlus = /^<[^>]+>.?/
NEW: rTagPlus = /^(<[^>]+>)+.?/

After my local fix, both FFX and IE started slicing the summary at the desired 235 text characters.

Thanks for writing such a great plug in!

problem with jquery expander in ie

i have a div with class expander. with in it many divs with text right inside them. i find that there is some 500 char in the first inner div and 50 char in the second inner div. i find that text is displayed on the first line and half in the second line. the more link appears in the third line which i dont want. i want the more link to appear right after the word ended in the second line. im using version 0.4 and no special characters in the text

Calling .expander() more than once

I have a situation where I'm implementing infinite scrolling (asynchronously loading more content as the user scrolls near the bottom of the page). I may need to collapse some of the newly loaded content. Currently, calling .expander() more than once results in some odd behavior on blocks that have already been collapsed. Here's my call:

$("p.expander").expander({
    slicePoint: 150,
    widow: 0,
    expandText: "[+]",
    expandPrefix: "",
    userCollapseText: "[-]",
    userCollapsePrefix: " "
});

So after loading the page and calling .expander() three times, here are the result on one of my paragraphs:

First call:

<p class="expander">Answer 12. Ut a dictum leo. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi <span class="read-more"><a href="#">[+]</a></span><span style="display: none;" class="details">tristique senectus et.<span class="re-collapse"> <a href="#">[-]</a></span></span></p>

Second call:

<p class="expander">Answer 12. Ut a dictum leo. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi <span class="read-more"><a href="#">[+]</a></span><span style="display: none;" class="details">tristique senectus et.<span class="re-collapse"> <a href="#">[-]</a></span><span class="re-collapse"> <a href="#">[-]</a></span></span></p>

Third call:

<p class="expander">Answer 12. Ut a dictum leo. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi <span class="read-more"><a href="#">[+]</a></span><span style="display: none;" class="details">tristique senectus et.<span class="re-collapse"> <a href="#">[-]</a></span><span class="re-collapse"> <a href="#">[-]</a></span><span class="re-collapse"> <a href="#">[-]</a></span></span></p>

Then I reloaded the page, called .expand() once, expanded my text, and called .expand() again. Here are the results:

First call:

<p class="expander">Answer 12. Ut a dictum leo. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi <span style="display: none;" class="read-more"><a href="#">[+]</a></span><span style="display: inline;" class="details">tristique senectus et.<span class="re-collapse"> <a href="#">[-]</a></span></span></p>

Second call, after expanding text:

<p class="expander">Answer 12. Ut a dictum leo. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi <span style="display: none;" class="read-more"><a href="#">[+]</a></span><span style="display: none;" class="details">tristique senectus et.<span class="re-collapse"> <a href="#">[-]</a></span><span class="re-collapse"> <a href="#">[-]</a></span></span></p>

Calling .expand() a third time added a third collapse link.

Is there a work-around or fix for this problem? Thanks.

Triggering 'read more/less' behavior using some other link or button click?

Hi,

Can I trigger the 'read more' / 'read less' behavior using some other link in my mark-up and passing it's class to the function?
I'm using the plugin to expand the content of a div, and at the same time I'm using fadeOut to reveal 6 more divs below this div. Now the 'read less' button still appears at the same position, in the top div, where the viewer would have to click it to hide the content and the rest of the divs. If I can append a 'read less' link to the bottom of the last div, and trigger the 'read less' behavior by clicking it, it would look neater! I tried appending a similar span > link markup with the same classes as the plugin generates, but it doesn't work.

Any ideas how I can do it ?

Thanks for any help!

Rutwick

Break in newline?

It could be great if there were a feature for breaking in the first newline instead of x character.

Breaking in a table

When the slice point is in the middle of a table, the read more link appears before the top of table.

Example of this behaviour here http://jsfiddle.net/fFdDW/4/

I fixed this locally by modifying the backup function to not break in the middle of a table.

function backup(txt, preserveWords) {
if ( txt.lastIndexOf('<') > txt.lastIndexOf('>') ) {
txt = txt.slice( 0, txt.lastIndexOf('<') );
}
if ( txt.toLowerCase().indexOf('<table') > -1 ) {
txt = txt.slice( 0, txt.toLowerCase().indexOf('<table') );
}
if (preserveWords) {
txt = txt.replace(rAmpWordEnd,'');
}
return $.trim(txt);
}

A more generalised solution would be to allow a user to configure any elements that should not be broken by the slice.

Thanks for jqueryexpander :-)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.