• Stars
    star
    178
  • Rank 214,989 (Top 5 %)
  • Language
    TypeScript
  • License
    ISC License
  • Created about 4 years ago
  • Updated over 1 year ago

Reviews

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

Repository Details

A < 750 byte Promise-based library for animating elements with dynamic heights open & closed. Basically, a modern variant of jQuery's slideUp(), slideDown(), and slideToggle().

slide-element

Bundle Size

A tiny, accessible, Promise-based, jQuery-reminiscent library for sliding elements with dynamic heights open & closed.

To see it in action, check out the following demos:

Why?

Using JavaScript to animate an element open and closed hasn't traditionally been a straightforward task, especially if it contains dynamically sized content. You could go with something like jQuery's slideToggle(), but that path would require you to take on a lot more code than necessary. Another option is using CSS to change the max-height value of an element, but this approach is filled with arbitrariness and difficult to pull off well when you're not sure how much content you'll be animating over.

This library gets the job done using the Web Animations API, and it doesn't require elements to have fixed heights. Instead, element heights are calculated based on their contents, and then the appropriate values are applied to trigger a smooth, native transition. The animations themselves are powered by the same mechanics used within CSS transitions, making it one of the best ways to pull it off in terms of performance.

It's small, smooth, and focuses on doing one job well: sliding stuff open and closed.

Installation

Run npm install slide-element, or use a CDN like unpkg.

Setup

Make sure your target element is set to display: none;.

Usage

Toggling Elements

Use the toggle function to slide an element open & closed based on its current state.

import { toggle } from "slide-element";

document.getElementById("button").addEventListener("click", (e) => {
  toggle(document.getElementById("box"));
});

Sliding Elements Down

Use the down function to slide an element open.

import { down } from "slide-element";

document.getElementById("button").addEventListener("click", (e) => {
  down(document.getElementById("boxToSlideOpen"));
});

Sliding Elements Up

Use the up function to slide an element closed, and then set its display property to none.

import { up } from "slide-element";

document.getElementById("button").addEventListener("click", (e) => {
  up(document.getElementById("boxToSlideClosed"));
});

Everything's a Promise

Each of the functions provided return promises, so you can easily wait to perform an action after an animation is complete. The resolved value will indicate if the element has just been opened (true), closed (false), or the result of an animation that interruped another (see more below).

import { toggle } from "slide-element";

document.getElementById("button").addEventListener("click", (e) => {
  toggle(document.getElementById("someElement")).then((isOpen: boolean | null) => {
    console.log("Toggling is done!");
  });
});

Interrupting In-Progress Animations

Depending on your settings, some users may be able to repeatedly trigger a new before a previous one has been allowed to finish, which will cause the in-progress animation instantly finish before the new one can begin.

When this occurs, the isOpen Promise that resolves after the animation is complete will return null for each animation that was triggered in interruption of the first. The initial animation, however will still resolve to the correct value. For example, pretend the following animation is clicked rapidly three times in a row.

import { toggle } from "slide-element";

document.getElementById("button").addEventListener("click", (e) => {
  toggle(document.getElementById("someElement")).then((isOpen: boolean | null) => {
    console.log(isOpen);
  });
});

When the animation has been allowed to complete, the following values will be logged -- two null values for the interrupting animations, and one boolean for the initial (and now complete) one. The point here is that it may be necessary to explicitly check for a non-null value when using the resolved "open" state.

true
null
null

Animating Boxes with Padding

If the element you're animating has any padding set to it, be sure to also apply box-sizing: border-box as well. If you don't, the resulting animation will be weird and jumpy.

<div id="myTarget" style="padding: 1rem; box-sizing: border-box; display: none;">
  My contents!
</div>

Customizing the Animation

By default, slide-element uses the following transition property values:

Property Value
duration (in milliseconds) 250
easing (choose one) ease

You can override these by passing an object as the seceond parameter of any method:

up(document.getElementById("element"), {
  duration: 500,
  easing: "ease-in-out",
});

Customizing the Opened display Value

Out of the box, slide-element will set your opened element to display: block;. If you'd like to customize this, pass a display value as an option:

down(document.getElementById("element"), {
  display: "flex"
});

Customizing the overflow Value Used During Animation

Out of the box, slide-element will animate your element open & closed with overflow: hidden;. If you'd like to pass your own value, use the overflow option:

down(document.getElementById("element"), {
  overflow: "auto"
});

Usage w/o a Bundler

If you'd like to use slide-element directly in the browser via CDN, simply load the code, and then reference the function you'd like to use on the global SlideElement object:

<script src="./path/to/slide-element.js"></script>
<script>
  document.getElementById('someElement').addEventListener('click', (e) => {
    SlideElement.toggle(document.getElementById("someBox"));
});
</script>

API

// Toggle an element based on current state.
toggle(element: HTMLElement, options?: object): Promise<boolean>

// Slide an element down.
up(element: HTMLElement, options?: object): Promise<boolean>

// Slide an element down.
down(element: HTMLElement, options?: object): Promise<boolean>
Param Type Description
element HTMLElement A single HTML node to be slid open or closed
options object Options to customize sliding animation.

Accessibility

This library will respect the prefers-reduced-motion setting on a user's machine. When it's set to reduce, the sliding animation will be forced to a duration of 0, making the respective elements open and close instantly.

Additionally, it's highly recommended that you toggle the aria-expanded attribute on any element (like a button) that's responsible for triggering an animation. This can be done by adding a single line of code that fires afters an animation is complete:

document.getElementById('someButton').addEventListener('click', (e) => {
    toggle(document.getElementById('thing2')).then((opened) => {

      <!-- Set the appropriate `aria-expanded` value based on the state of the container. -->
      e.target.setAttribute("aria-expanded", opened);
    });
  });

Show Off Your Use Case

I love to see examples of how you're using the stuff I build. If you're comfortable, please send it my way!

More Repositories

1

typeit

The most versatile JavaScript typewriter effect library on the planet.
JavaScript
3,056
star
2

wp-vue

A simple Vue blog template that displays posts from any WordPress REST API endpoint.
Vue
458
star
3

local-docker-db

A bunch o' Docker Compose files used to quickly spin up local databases.
Go
284
star
4

striff

Real simple string diffing.
TypeScript
203
star
5

christian-git

A wrapper for Git to sanctify your version control workflow. ✝️
JavaScript
99
star
6

netlify-lambda-function-example

An example Netlify Lambda function that processes payments with Stripe.
JavaScript
97
star
7

probaclick

Do something when someone is probably going to click something.
JavaScript
78
star
8

wp-skateboard

My local WordPress development built with Docker and Docker Compose.
Shell
58
star
9

typeit-react

A React component for TypeIt, the most versatile JavaScript animated typing utility on the planet.
TypeScript
34
star
10

vite-plugin-proxy-page

A Vite plugin for projecting your application onto a remote page during development.
TypeScript
28
star
11

wp-complete-open-graph

A WordPress plugin for simple, comprehensive, customizable Open Graph management.
PHP
25
star
12

gatsby-source-dropbox-paper

A source plugin for Gatsby that pulls data from the Dropbox Paper API.
JavaScript
24
star
13

current-time-api

Keep your website's footer up-to-date with ease.
TypeScript
22
star
14

graphql-quest

Ultra-minimal library for making GraphQL requests in the browser and Node (with a quick polyfill).
TypeScript
20
star
15

wp-better-resource-hints

A WordPress plugin to help better manage resource hinting (preloading, prefetching, server pushing).
PHP
18
star
16

css-by-js

Turn your CSS into JS that turns it into inline CSS.
JavaScript
10
star
17

macarthur-me-astro

My site built with Astro.
Astro
9
star
18

wp-typeit

Easily add typewriter effects to your WordPress site with TypeIt, the most versatile animated typing utility on the planet.
PHP
8
star
19

cloudflare-image-proxying

The Cloudflare Worker I use to serve Notion images on my statically-generated website.
TypeScript
7
star
20

jam-comments-javascript

A monorepo for the JamComments packages that power the JavaScript-based integrations.
TypeScript
6
star
21

power-plant

A dependency injection framework built on native decorators.
TypeScript
5
star
22

macarthur-me-next

My site on NextJS.
TypeScript
4
star
23

wp-plugin-update-lambda

A Vercel serverless function for managing WordPress plugin updates.
TypeScript
4
star
24

macarthur-me-gatsby

My website, built with Gatsby.
JavaScript
3
star
25

wp-sniff

A Python script that searches a site's source code for signs that it runs on WordPress.
Python
3
star
26

binding-pry-js

binding.pry for JavaScript, for the Ruby devs who can't shake the habit.
JavaScript
3
star
27

scrappy

A simple, scrappy set up for testing page performance with different front-end scenarios.
HTML
3
star
28

gatsby-plugin-jam-comments

The official plugin for easily integrating JamComments into your Gatsby blog.
JavaScript
2
star
29

statamic-picperf

PHP
2
star
30

image-transformation-demo

A Cloudflare Worker demonstrating how to transform image URLs for use with PicPerf.io.
JavaScript
2
star
31

picperf-javascript

JavaScript utilities for using PicPerf.dev.
TypeScript
2
star
32

picperf-wordpress

WordPress plugin for upgrading your images with PicPerf.io.
PHP
2
star
33

typeit-site-gatsby

The official site for TypeIt, the most versatile JavaScript typewriter effect library on the planet.
JavaScript
2
star
34

jQuery-CenterIt

A very simple jQuery plugin that vertically & horizontally centers a selected element within the parent element.
JavaScript
2
star
35

bundler-experiments

Just experimenting with bundlers like Rollup, Webpack, and Parcel.
JavaScript
1
star
36

jekyll-jam-comments

A Ruby gem for setting up JamComments in your Jekyll site.
Ruby
1
star
37

browser-unload-testing

Exploring what happens to AJAX requests when the browser is about to unload.
HTML
1
star
38

eleventy-plugin-jam-comments

The official plugin for easily integrating JamComments into your Eleventy blog.
JavaScript
1
star
39

vite-proxy-demo

A demo for using Vite to proxy/project a small SPA onto a deployed, production page during local development.
HTML
1
star
40

dom-updates-and-browser-repaints

A playground for experimenting with DOM updates and how they impact browser repaints.
HTML
1
star
41

github-actions-sandbox

A repo for getting started with GitHub Actions.
JavaScript
1
star
42

alexmacarthur

My personal README.
1
star
43

preload-testing

A little sandbox for experimenting with asset preloading.
HTML
1
star
44

jam-comments-site

The marketing site for JamComments.
Nunjucks
1
star
45

expand-text-nodes

Expand text within HTML to be composed of one text node per character.
JavaScript
1
star
46

typeit-site-docusaurus

The website for typeitjs.com.
TypeScript
1
star
47

generate-magnolia-key

Run a command to generate a Magnolia key and update your local public instance.
JavaScript
1
star
48

wp-sahlstroms

Wordpress theme designed & developed for a local HVAC company.
PHP
1
star
49

rudimentary-react

A bare-bones React starter built on Vite.
JavaScript
1
star
50

speed-limit-with-cloudflare

1
star
51

map-everything

Add a map() method to the prototypes of Object, String, Set, and Map.
JavaScript
1
star
52

color

A tiny Svelte app for rendering colors in the browser.
Svelte
1
star
53

alexmacarthur.github.io

Built with Jekyll.
HTML
1
star
54

bridgetown-jam-comments

The official Bridgetown plugin for JamComments.
Ruby
1
star