简体中文 | English
A dependency-free H5 (mobile web) touch / mouse sliding component: paging, centred item picking, native-like scrolling, swipe-to-reveal list items, free dragging, and pinch-to-zoom.
- Zero runtime dependencies, no jQuery required.
- CSS
transform: translate3d(...)+ CSS transitions, no animation framework. - One UMD source of truth: loadable via
<script>, AMD, orrequire(). - Handwritten TypeScript declarations and a DOM-stub test suite.
Project home · Repository · Demos
| File | Notes |
|---|---|
dist/jmslip.js |
Recommended for browsers. UMD build, exposes window.jmSlip. Regenerated by npm run build. |
src/jmSlip.js |
The single source of truth. UMD as well, so it can also be loaded directly with a classic <script> tag; require('jmslip') resolves here. |
dist/jmslip.es6.js |
ES module with a default export; use with <script type="module"> or a bundler, not a classic script. |
dist/*.min.js |
Minified variants. Without terser installed, the build emits uncompressed content with an explicit header (see Development). |
<script src="../../dist/jmslip.js"></script>The component itself has no dependencies. The pages under demo/ use a tiny local helper (demo/dom.js) for their own UI code instead of any external library, and the root index.html also has no third-party dependency — none of it is required by jmSlip.
The component expects a container whose first child wraps the sliding items:
<section id="banner" class="banner">
<ul>
<li>Slide 1</li>
<li>Slide 2</li>
<li>Slide 3</li>
</ul>
</section>
<script src="dist/jmslip.js"></script>
<script>
var slip = new jmSlip('banner', 'page', {
direction: 'x',
loop: true
});
window.addEventListener('resize', function () {
slip.reset();
});
// later: slip.destroy();
</script>index.d.ts is shipped and declared through types / exports. Because the package uses module.exports = fn, use import = require (or esModuleInterop with a default import):
import jmSlip = require('jmslip');
// with esModuleInterop: import jmSlip from 'jmslip';
const options: jmSlip.PageOptions = {
mode: 'page',
direction: 'x',
loop: true,
onPageEnd(oldPage, page) {
console.log(oldPage, '->', page); // page is always a number
}
};
const slip: jmSlip.Instance = new jmSlip('banner', options);
slip.go(1);
slip.reset();
slip.destroy();Exported types: Mode, ElementLike, Offset, GestureEvent, Callbacks, CommonOptions and mode-specific PageOptions / ItemOptions / ScrollOptions / ScrollItemOptions / DragOptions / ScaleOptions (union Options), plus Instance. window.jmSlip is typed for classic-script usage. Callback this is typed as the mode implementation object.
new jmSlip(el, mode, option)
new jmSlip(el, option) // option.mode is used as the mode
new jmSlip(el, null, option) // falls back to option.mode || 'page'| Argument | Details |
|---|---|
el |
An id string (resolved with getElementById, not a CSS selector), a native DOM node, or any array-like object with length and [0] (jQuery / Zepto object, NodeList). Invalid elements and containers without a first child throw a TypeError. |
mode |
One of the six modes below. Defaults to 'page'. The source calls this argument mode; older docs called it type. An unknown value throws a TypeError listing the valid modes. |
option |
Configuration object. The constructor copies it before applying defaults, so the caller's object is never mutated and is safe to reuse. |
| Mode | Behaviour | Typical use |
|---|---|---|
page (default) |
Full-page switching, optional loop / repeat |
Carousels, full-screen onboarding |
item |
A row of items scrolls so that one item is centred and selected | Date pickers, centred selectors |
scroll |
Native-scrollbar-like dragging with boundary bounce | Scrollable panels |
scrollItem |
Each list item can be pulled aside to reveal actions | WeChat-style swipe-to-delete rows |
drag |
Free dragging of the element; the event container becomes document |
Floating buttons that snap to an edge |
scale |
Two-finger pinch zoom, optional one-finger panning, wheel zoom | Image viewers |
| Option | Default | Description |
|---|---|---|
direction |
vertical | Only the exact value 'x' enables horizontal movement; any other value (including 'y') means vertical. Applies to page, item, scroll and scrollItem. |
duration |
500 |
CSS transition duration in ms (converted to seconds internally). 0 is valid (no animation). |
minOffset |
30 |
Minimum drag distance (px) that triggers a page change / inertial scroll. Per instance, numbers or numeric strings; 0 is valid and disables the extra step. |
itemOffWidth, itemOffHeight |
0 |
Extra width / height added per item, e.g. to account for margins. |
zIndex |
10000 |
z-index applied to pages in page mode; 0 is valid. |
page |
0 |
Initial page / item index. |
changeTime |
off | Auto-advance interval in ms; falsy disables auto-play. |
mousewheel |
off | Enables wheel input on this instance's element. The library detects support and binds exactly one of wheel / mousewheel / DOMMouseScroll, so a single scroll is never applied twice. |
locked |
off | page mode: prevent dragging beyond the boundaries. |
animate |
'page' in page mode |
item mode also accepts 'default' / 'flip' for the selection animation. |
width, height |
measured | Override the page size in page mode. |
paddingRight, paddingBottom |
0 |
Extra scrollable space in scroll mode. |
mode |
'page' |
Alternative to the second constructor argument. |
Numeric options are validated; non-finite or out-of-range values throw RangeError instead of silently producing NaN.
| Option | Mode | Description |
|---|---|---|
loop |
page |
Wrap around from the last page to the first. With exactly two pages the DOM is cloned with cloneNode. |
repeat |
page |
Lay out all pages side by side and move them as a strip. A different mechanism from loop — do not combine them. |
selectHandler(curIndex, newIndex) |
item |
Override selection: return a number to choose another index, or false to keep the current one. |
target |
scale |
The element to transform (e.g. an <img> inside the container). |
supportTranslate |
scale |
Allow one-finger panning in addition to pinch zoom. |
maxScale, minScale |
scale |
Zoom limits; 0 is valid. |
orientation |
scrollItem |
Swipe direction: left, right, top, bottom. |
maxOffset |
scrollItem |
Maximum distance (px) an item can be pulled aside. |
itemSelector |
scrollItem |
Selector used to find the draggable child inside a touched row (real closest() semantics). |
In all touch callbacks, this is the mode implementation object (slip.slipObj), not the instance returned by new jmSlip(...). That is why this.move(...), this.offsetX and this.instance work inside callbacks while slip.move(...) does not.
| Callback | Signature | Fired when | return false |
|---|---|---|---|
onTouchStart |
(evt) |
Gesture starts | Skips the gesture and resets the touched state. |
onTouchMove |
(evt, offset) |
Every move; offset is { offx, offy }, the absolute displacement from the start point (not a delta) |
Skips only this displacement — it no longer synthesises a touch-end. |
onTouchEnd |
(evt, offset) |
Gesture ends | Cancels only the final action. Transition, touched state and auto-play are still restored, so the component cannot get stuck. |
onPageStart |
(page, oldPage, actionType) (both page and item) |
Before switching pages | Cancels the switch without recursion. Returning a number overrides the target page in either mode. |
onPageEnd |
(oldPage, page, actionType) |
After the switch | Ignored. page is always a number in both modes. |
onScrollEnd |
scroll: (offsetX, offsetY, xdir, ydir, evt); scrollItem: (tx, ty, xdir, ydir, evt, target) |
Scrolling settles | Ignored. tx / ty are always numbers. |
onScaleStart, onScaleEnd |
(per, evt) |
Before / after a zoom step | onScaleStart can cancel the zoom. evt is now passed through and this is the mode object, consistent with other callbacks. |
dragEnd |
(offx, offy) |
A drag finishes | Ignored. this.offsetX / this.offsetY / this.move() are available. |
selectHandler |
(curIndex, newIndex) |
item selection |
Number overrides the target; false keeps the current page. |
| Method | Description |
|---|---|
go(index) |
Jump to a page / item. |
reset() |
Recalculate sizes and restore positions — call it after a window resize or after the container becomes visible. It does not rebind events or restart auto-play. |
destroy() |
Detach every listener (including the single bound wheel listener), clear the auto-play and wheel timers, and release the last touched row. Returns the instance. |
destory() |
Deprecated misspelled alias, kept for backwards compatibility. |
bindEvent(enable?), transition(...), setStyle(...), auto() |
Internal helpers that happen to be public; avoid depending on them. bindEvent() is idempotent. |
slip.slipObj |
The mode implementation object. Methods such as move, offset, next, previous and scale live here, not on the instance. |
var slip = new jmSlip('banner', 'page', {
direction: 'x',
loop: true,
mousewheel: true,
onPageStart: function (page) {
console.log('leaving for page', page);
},
onPageEnd: function (oldPage, newPage) {
console.log(oldPage, '->', newPage);
}
});repeat: true lays out all pages as a strip instead of wrapping the index. See demo/page/x.html and demo/page/y.html.
var slip = new jmSlip('banner', 'item', {
direction: 'x',
page: 0,
duration: 800,
itemOffWidth: 1,
selectHandler: function (curIndex, newIndex) {
if (newIndex > 2) return 2; // clamp to the third item
},
onPageEnd: function (oldPage, newPage) {
console.log('selected', newPage);
}
});See demo/item/index.html and demo/calendar/index.html.
var slip = new jmSlip('wrap', 'scroll', {
minOffset: 0,
itemOffWidth: 8,
onScrollEnd: function (offsetX, offsetY) {
console.log(offsetX, offsetY);
}
});var slip = new jmSlip('list', 'scrollItem', {
orientation: 'left',
maxOffset: 80,
itemSelector: '.js-slip-item'
});See demo/scroll/scroll_item.html.
var entry = document.getElementById('act-enter');
var slip = new jmSlip(entry, 'drag', {
onTouchStart: function (e) {
if (e && e.preventDefault) e.preventDefault();
},
dragEnd: function (offx, offy) {
var rect = entry.getBoundingClientRect();
var center = rect.left + rect.width / 2;
var winw = window.innerWidth;
if (center <= winw / 2) offx -= rect.left; // snap left
else offx += winw - center - rect.width / 2; // snap right
this.move(offx, offy); // `this` is the drag implementation object
}
});See demo/drag/index.html.
var container = document.getElementById('viewer');
var slip = new jmSlip(container, 'scale', {
target: container.querySelector('img'),
supportTranslate: true,
maxScale: 4,
minScale: 0.1,
mousewheel: true,
onScaleStart: function (per) {
console.log('scale:', per);
}
});- Event source is chosen once via
'ontouchstart' in windowornavigator.maxTouchPoints > 0: touch or mouse, never both. There is no Pointer Events support, so hybrid devices cannot use both input types.attachEventis used as an IE8 fallback. - Listeners are registered with
{ passive: false }when supported, and the container getstouch-action: none, sopreventDefault()works on Chrome/Android instead of the page scrolling along with the gesture. touchstartbinds to the target,touchmove/touchend/touchcancelto the container (todocumentindragmode). On desktop,mouseupis bound to the container, so releasing the pointer outside it loses the event.- Coordinates prefer
clientX/clientYbut keep a legitimate0instead of falling back topageX/pageY. - All movement uses CSS
transform: translate3d(...), written throughsetPropertyfor hyphenated names. The needed vendor prefix is detected once, so modern browsers get one style write per move instead of five. Easing comes from CSStransition. - Wheel input is normalised across
wheelDelta,deltaYand Firefoxdetail. Chrome fires bothwheeland legacymousewheelfor one scroll, so only one supported event name is bound; listeners belong to the instance's element, notdocument, so multiple instances do not interfere. data-pageattributes are written on initialisation andpageEndcallbacks receive numeric indices.
npm test # node test/index.js — 19 DOM-stub assertion checks
npm run build # node scripts/build.js — regenerate all four dist/ files from src/
npm i -D terser # optional: enable real minification for dist/*.min.jssrc/jmSlip.js is the only file you should edit; npm run build derives the UMD and ESM bundles so dist/ cannot drift behind it. The legacy build/ directory contains the historical gulp setup and is no longer the primary build path.
- No Pointer Events / no true inertia. Touch and mouse remain mutually exclusive;
scrollmode adds a fixedminOffsetstep rather than velocity-based momentum, and there is norequestAnimationFramethrottling. Very large lists still need virtualization. A full Pointer Events + rAF rewrite would change multi-touch handling inscalemode and needs real-device verification before being shipped. - Desktop edge case:
mouseupis bound to the container, so releasing the mouse outside it can leave the gesture open. - Partially wired helper:
pageSlip.pageEnd()(lazy image loading / animation hooks) is commented out inpagemode but still invoked byitemmode;pagedemos implement it inonPageEnd. - Experimental options:
animate: 'flip',lockedand a few mode-specific knobs are exercised by demos but not covered by automated tests. - Build artefacts:
dist/*.es6.jsare ES modules (not classic scripts). Withoutterser, the.min.jsfiles are uncompressed and carry an explicit header. - Test coverage: the suite uses a DOM stub, not a real browser. Verify gestures on target devices before release.
| Demo | Mode |
|---|---|
| demo/page/x.html, demo/page/y.html | page |
| demo/item/index.html, demo/calendar/index.html | item |
| demo/scroll/index.html, demo/scroll/scroll_item.html | scroll, scrollItem |
| demo/drag/index.html | drag |
| demo/scale/index.html | scale |
| demo/emoji/index.html, demo/cyzm/index.html | Full-page showcases |