Accordion-like Content Toggle Plugin With jQuery - toggleWidget

File Size: 8.32 KB
Views Total: 1596
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Accordion-like Content Toggle Plugin With jQuery - toggleWidget

A simple, lightweight, customizable jQuery content toggle plugin which uses CSS3 transitions to smoothly show/hide content blocks just like the accordion. Also supports auto scrolling the viewport to the top position of your content blocking when toggling.

How to use it:

1. Create the content which is hidden on page load.

<div class="demo__content toggle-widget__content">
  <div class="demo__content-inner toggle-widget__content-inner">
    Content here
  </div>
</div>

2. Create a toggle button to show the content on click.

<button type="button" class="demo__toggle-btn toggle-widget__toggle-btn">Toggle</button>

3. The plugin requires the latest version of jQuery library (slim build is recommended) to work correctly.

<script src="//code.jquery.com/jquery-3.1.1.slim.min.js"></script>
<script src="jquery.toggle-widget.js"></script>

4. Active the plugin with default options.

$('.toggle-widget').toggleWidget();

5. The required CSS to hide the content block by setting the height to 0, and then apply the CSS transition effect to it when toggling.

.toggle-widget__content {
  height: 0;
  transition: height .3s;
  overflow: hidden;
}

6. Active the plugin with default options.

$('.toggle-widget').toggleWidget();

7. Configuration options with default values.

$('.toggle-widget').toggleWidget({

  // enable or disable the widget
  enabled: true,

  // CSS classes
  toggleBtnSelector: '.toggle-widget__toggle-btn',
  toggleContentSelector: '.toggle-widget__content',
  openClass: 'toggle-widget--open',

  // shift the offset top value by this before returning.
  offsetTopShift: -20,

  // animation duration in milliseconds
  scrollDuration: 300
  
});

8. API methods.

// open the content
$('.toggle-widget').toggleWidget('open');

// close the content
$('.toggle-widget').toggleWidget('close');

// toggle the content
$('.toggle-widget').toggleWidget('toggle');

// enable the plugin
$('.toggle-widget').toggleWidget('enable');

// disable the plugin
$('.toggle-widget').toggleWidget('disable');

// get offset top value shifted by 'offsetTopShift'
$('.toggle-widget').toggleWidget('getOffsetTop');

// get the height of the content-inner element 
$('.toggle-widget').toggleWidget('getContentInnerHeight');

// scroll the viewport to the offset top position
$('.toggle-widget').toggleWidget('scrollToOffsetTop');

// returns whether the toggle is open
$('.toggle-widget').toggleWidget('isOpen');

// destroy the plugin
$('.toggle-widget').toggleWidget('destroy');

Change log:

2017-01-26

  • added isOpen method.

This awesome jQuery plugin is developed by floriancapelle. For more Advanced Usages, please check the demo page or visit the official website.