• Stars
    star
    460
  • Rank 95,202 (Top 2 %)
  • Language
    JavaScript
  • License
    Other
  • Created about 15 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Expand and Collapse HTML content

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.

More Repositories

1

jquery-smooth-scroll

Automatically make same-page links scroll smoothly
JavaScript
1,970
star
2

jquery-tmbundle

TextMate bundle for jQuery
XML
562
star
3

jquery-cluetip

No longer maintained/supported. โ€” Displays a highly customizable tooltip when the user hovers (default) or clicks (optional) the matched elements.
JavaScript
219
star
4

jquery-carousel-lite

A jQuery carousel plugin based on jCarouselLite by Ganeshji Marwaha
JavaScript
179
star
5

grunt-version

Handle versioning of a project using grunt
JavaScript
51
star
6

jquery-tinyvalidate

A (relatively) tiny form validation plugin
JavaScript
16
star
7

jquery-fancyletter

A jQuery plugin that lets you prettify your web page by styling the first letter of any element
JavaScript
12
star
8

jQuery-API-Search

JSONP API for searching the jQuery API at http://api.jquery.com/
JavaScript
10
star
9

jquery-defaulttext

sets default text overlay on top of a text input
JavaScript
8
star
10

ks.markitup.fieldtype.ee_addon

A markItUp field type for the Field Frame ExpressionEngine extension
JavaScript
8
star
11

jQuery-sameHeight

makes collection of elements all the same height
JavaScript
7
star
12

ks.clearcache.ee_addon

ExpressionEngine module to clear cache from front-end using ajax
6
star
13

jquery-summarize

A simple plugin to initially display only a certain number of children, with a "read more" link
JavaScript
6
star
14

jquery-biglinks

jQuery plugin to increase the target area of links to a containing element
JavaScript
6
star
15

jquery-socialize

jQuery Plugin for adding a group of social bookmarks to a blog post
5
star
16

hotspotter.ee_fieldtype

Image "Hotspot" fieldtype for Expression Engine's Field Frame extension
JavaScript
5
star
17

dotfiles

dot files for my MBP
Shell
5
star
18

new-tab-bookmarks

Chrome extension to show bookmarks (from folder of your choice) in new tab
Vue
5
star
19

atom-jquery

A collection of jQuery snippets derived from my TextMate bundle
CSS
4
star
20

ks.facelift.ee_addon

Uses Facelift Image Replacement script (w/o JavaScript) to convert text to images
PHP
4
star
21

ump

Version bumping without the b
JavaScript
4
star
22

jquery-columns

puts children of a containing element into the number of columns that you specify (and deals with <ol> numbering)
JavaScript
4
star
23

fusionary-tmbundle

TextMate bundle for HTML, CSS, and JavaScript to make work at Fusionary more streamlined.
4
star
24

ks.slashee.ee_addon

ExpressionEngine plugin to add or remove starting and/or ending slashes for a string
3
star
25

ks.karls-extra-head.ee_addon

ExpressionEngine extension allowing user to add any html to the end of the document head for control panel pages
2
star
26

blog.karlswedberg.com

A blog about some techie things
JavaScript
2
star
27

triib-scrape

CLI tool to extract all Triib members' workout history
JavaScript
2
star
28

ksjs

Random js functions
JavaScript
1
star
29

c2md

Output HTML clipboard contents to markdown in the terminal (MacOs only)
JavaScript
1
star
30

dotatom

My .atom files, sourced.
JavaScript
1
star
31

grwebdev-201707

Presentation for GRWebDev Meetup, 25 July 2017
JavaScript
1
star
32

tagify.ee_addon

ExpressionEngine (EE) plugin to convert [tagname param="foo"] to {tagname param="foo"} in entry field so it can be parsed by EE
PHP
1
star