@modracx/marquee-js
v1.0.0
Published
Lightweight seamless marquee / ticker for web pages — any direction, drag to scroll, pause on hover, edge fades, and reduced-motion aware. Zero dependencies.
Maintainers
Readme
@modracx/marquee-js
Seamless scrolling marquee / ticker for the web. Any direction, drag to scroll, pause on hover, edge fades, and it holds still when the OS asks for reduced motion. Zero dependencies, no build step, ~13 KB of source.
Not the deprecated <marquee> tag — this measures your content, tiles enough
copies to cover the viewport, and drives a translate3d on a single rAF loop,
so the loop point is invisible and the speed is the same on a 60 Hz laptop and
a 144 Hz monitor.
npm install @modracx/marquee-jsimport Marquee from "@modracx/marquee-js";
Marquee.create(document.querySelector("#logos"), {
speed: 60, // px per second
gap: 40, // px between items
pauseOnHover: true,
fadeEdges: true,
});Every direct child of the container becomes one marquee item. Nothing else is required — no wrapper markup, no CSS to copy in.
Contents
- Why not CSS keyframes
- Options
- The controller
- Declarative setup
- Right-to-left
- Item margins vs gap
- jQuery
- Granular API
- Recipes
- Accessibility
- How the seamless loop works
- Browser support
Why not CSS keyframes
The usual @keyframes scroll { to { transform: translateX(-50%) } } trick is
fine until you need any of this:
| | CSS keyframes | marquee-js |
| --- | --- | --- |
| Change speed at runtime | restarts the animation | setSpeed(), no jump |
| Reverse direction | restarts | setDirection() |
| Drag to scroll | not possible | pointer events, any input |
| Pause offscreen | still burns CPU | IntersectionObserver |
| Content of unknown width | you hardcode -50% | measured at runtime |
| Items added later | recalculate by hand | addItem() |
| Flick to scroll on touch | not possible | momentum, dragDecay |
| Setup with no JS at all | needs handwritten CSS | data-marquee attributes |
If none of those matter, use CSS. It is lighter.
Options
All options go in one object; create() splits them across the three layers.
Engine
| Option | Type | Default | Notes |
| --- | --- | --- | --- |
| direction | "left" \| "right" \| "up" \| "down" | "left" | Vertical directions lay the track out as a column. |
| speed | number | 60 | CSS px per second. Frame-rate independent. |
| gap | number | 40 | Px between items. Applied as flex gap, and counted in the repeat distance. See Item margins vs gap. |
| autoplay | boolean | true | false starts paused under the reason "manual". |
| respectReducedMotion | boolean | true | Holds still under prefers-reduced-motion: reduce, and reacts if the user changes it. |
| pauseOnHidden | boolean | true | Pauses on visibilitychange and when scrolled out of view. |
| observeResize | boolean | true | ResizeObserver on the container and each item, coalesced to one measure per frame. |
| dragDecay | number | 4 | How fast a flick decays, in e-folds per second. Higher stops sooner. |
Interaction
| Option | Type | Default | Notes |
| --- | --- | --- | --- |
| pauseOnHover | boolean | true | |
| hoverSpeed | number | null | null | Slow to this px/second on hover instead of stopping. See below. |
| pauseOnFocus | boolean | true | Keyboard users tabbing through links inside. |
| draggable | boolean | false | Mouse, touch and pen via pointer events. |
| dragThreshold | number | 4 | Px before a drag counts as a drag; below it, a click still fires. |
| momentum | boolean | true | A flick coasts to a stop after the pointer lifts. |
| keyboard | boolean | false | Arrow keys nudge, space toggles. Adds a tabindex. |
| keyboardStep | number | 40 | Px per arrow-key press. |
| showPauseButton | boolean | false | Renders a real <button> over the marquee. |
| pauseButtonPosition | string | "bottom-right" | Any of the four corners. |
| pauseButtonLabels | object | Pause / Resume | Accessible names for the two states. |
hoverSpeed and pauseOnHover are mutually exclusive
A marquee cannot both stop and slow down on hover, so hoverSpeed requires
pauseOnHover: false and attachControls throws if you ask for both.
Because pauseOnHover defaults to true, passing only hoverSpeed to
create() is read as declining the other, and pauseOnHover is switched off
for you:
Marquee.create(el, { hoverSpeed: 10 }); // fine
Marquee.create(el, { hoverSpeed: 10, pauseOnHover: false }); // same thing
Marquee.create(el, { hoverSpeed: 10, pauseOnHover: true }); // throwsattachControls makes no such allowance — call it with both and it throws.
Effects
| Option | Type | Default | Notes |
| --- | --- | --- | --- |
| fadeEdges | boolean | false | Fades both ends with a CSS mask, so it works over any background. |
| fadeSize | number | 48 | Px per fade. |
The controller
create() returns a controller. You can also fetch it later with
Marquee.get(container), which returns null if there is no marquee.
const m = Marquee.create(el, { speed: 80 });
m.stop();
m.start();
m.toggle();
m.setSpeed(120); // px/second, live
m.setDirection("up"); // re-lays out if the axis changes
m.setOffset(0); // jump within one content set
m.addItem(node); // append + re-measure
m.removeItem(node); // remove + re-measure
m.update(); // re-measure after your own DOM edits
m.glide(600); // coast from a flick, px/second in offset space
m.destroy(); // restores the original DOM exactlyRead-only:
| Property | Type | Meaning |
| --- | --- | --- |
| paused | boolean | Is anything holding it still. |
| pausedBy | string[] | Which reasons, e.g. ["hover", "offscreen"]. |
| offset | number | Position within one content set, px. |
| setSize | number | Repeat distance of one content set, px. |
| gliding | boolean | Is momentum from a flick still playing out. |
| settings | object | Live settings. Change via the setters. |
| track | Element | The generated track holding items and clones. |
| container | Element | The element the marquee is bound to. |
Pause reasons
Pausing is tracked by reason, not by a boolean, so the sources compose. Hover, focus, drag, tab visibility, offscreen and reduced-motion each hold their own reason; the marquee resumes only when every reason is released.
That is why hovering a marquee you already stopped does not restart it when the pointer leaves:
m.stop(); // reason: "manual"
// user hovers and leaves // adds then removes "hover"
m.paused; // still true — "manual" is still heldpause(reason) and resume(reason) are public if you want your own:
m.pause("modal-open");
// ...later
m.resume("modal-open");Declarative setup
The standalone vanilla/ and jquery/ builds call autoInit(document) on
DOMContentLoaded, so a marquee can be built with no script of your own —
which is what makes this usable from a CMS, a page builder, or any template
you cannot attach JavaScript to.
<div data-marquee data-marquee-speed="40" data-marquee-fade-edges>
<div>Acme</div>
<div>Globex</div>
</div>Attribute names are the option names in kebab-case. Values are coerced:
"40" becomes a number, "true" / "false" become booleans, and a valueless
attribute (data-marquee-fade-edges) reads as true.
data-marquee itself may hold a JSON object, which the individual attributes
then override:
<div data-marquee='{"speed":80,"gap":24}' data-marquee-direction="right">The npm package does not auto-run — a module with side effects on import is a poor citizen in a bundle. Call it yourself:
import Marquee from "@modracx/marquee-js";
Marquee.autoInit(); // whole document
Marquee.autoInit(someContainer); // or a subtreeIt skips elements that already have a marquee and returns the controllers it created, so it is safe to call again after inserting content.
Right-to-left
RTL is detected from the computed direction of the container, so dir="rtl"
on the element or any ancestor is enough — there is no option to set.
Direction names stay visual, not logical: "left" scrolls visually left in
both LTR and RTL. This matters because an RTL flex row lays its first child out
on the right and a max-content block overflows leftwards, which inverts both
the measurement and the transform internally.
If you want the marquee to follow reading order instead, pick the direction from the same source your layout does.
Item margins vs gap
Spacing between items comes from flex gap on the track. Margins on your
items are added on top of it, they do not replace it — an item with
margin: 0 20px inside a marquee with gap: 40 sits 80px from its neighbour.
This is usually not what people expect when they port existing markup in. The
marquee still loops seamlessly either way, because the repeat distance is
measured from the laid-out result rather than computed from gap. But if the
spacing looks doubled, that is why. Pick one:
Marquee.create(el, { gap: 0 }); // keep your margins, drop the gap#marquee > * { margin: 0; } /* keep the gap, drop the margins */Margins on the scroll axis of the last item are the one case that does
change the loop: they land between the last item and the first clone, on top of
the gap. Symmetrical margins are fine; a one-sided margin-right on the final
item will read as a wider seam.
jQuery
jQuery is an optional peer dependency. The plugin entry registers
$.fn.Marquee against a global jQuery when it is imported:
import "@modracx/marquee-js/jquery";
$(".ticker").Marquee("create", { speed: 90, fadeEdges: true });With a bundled jQuery that is not on window, register it yourself:
import registerMarqueePlugin from "@modracx/marquee-js/jquery";
import $ from "jquery";
registerMarqueePlugin($);Methods that act are chainable across the whole set:
$(".ticker").Marquee("create", opts);
$(".ticker").Marquee("start");
$(".ticker").Marquee("stop");
$(".ticker").Marquee("toggle");
$(".ticker").Marquee("update");
$(".ticker").Marquee("setSpeed", 120);
$(".ticker").Marquee("setDirection", "right");
$(".ticker").Marquee("setOffset", 0);
$(".ticker").Marquee("destroy"); // "clear" is a synonymMethods that read return a value from the first element in the set:
$(".ticker").Marquee("get"); // controller, or null
$(".ticker").Marquee("paused"); // boolean
$(".ticker").Marquee("offset"); // numberAn action on an element with no marquee throws rather than failing quietly.
$.Marquee is also exposed as a plain object for callers that skip the plugin.
Granular API
create() is a convenience over three independent layers. Use them directly
when you want the engine without the interaction, or want to attach your own.
import { createMarquee, attachControls, applyEdgeFade } from "@modracx/marquee-js";
const m = createMarquee(el, { direction: "up", speed: 35 });
attachControls(m, { draggable: true, pauseOnHover: false });
applyEdgeFade(m, { fadeEdges: true, fadeSize: 64 });attachControls returns its own cleanup and registers it with the controller,
so destroy() still tears everything down.
| Export | Purpose |
| --- | --- |
| create / clear | The composed entry points. |
| createMarquee / clearMarquee / getMarquee | Engine only. |
| attachControls | Hover, focus and drag. |
| applyEdgeFade | Edge mask; call with fadeEdges: false to remove. |
| prefersReducedMotion | The media-query check, exported for your own use. |
| defaults, marqueeDefaults, controlDefaults, effectDefaults | Read or mutate the defaults. |
Recipes
Logo wall
Marquee.create(el, { speed: 40, gap: 48, fadeEdges: true });News ticker, right to left, never pausing
Marquee.create(el, { speed: 90, pauseOnHover: false, pauseOnFocus: false });Vertical testimonial column, draggable
Marquee.create(el, { direction: "up", speed: 30, gap: 16, draggable: true });Two rows scrolling opposite ways
Marquee.create(rowA, { direction: "left", speed: 50 });
Marquee.create(rowB, { direction: "right", speed: 50 });Pause while a modal is open
const m = Marquee.get(el);
openModal(() => m.pause("modal"), () => m.resume("modal"));Rebuild after replacing the content wholesale
el.innerHTML = newMarkup; // wipes the track too
Marquee.create(el, opts); // create() clears any previous marquee firstFor incremental changes prefer addItem / removeItem / update, which keep
the current scroll position.
Accessibility
Reduced motion. On by default. The marquee renders its content but does not move, and it listens for changes to the setting rather than only reading it once at startup.
Clones are hidden from assistive tech. Every clone gets
aria-hidden="true"andinert(falling back totabindex="-1"on focusable descendants whereinertis unsupported), so screen readers read the content once and tab order visits it once.Pause on focus. On by default, so a keyboard user tabbing into a link inside the marquee is not chasing a moving target.
A real pause control. WCAG 2.2.2 asks for a way to pause any motion lasting more than five seconds, and
pauseOnHoverdoes not satisfy it — it is unreachable by keyboard, touch and screen reader alike. SetshowPauseButton: trueand you get an actual<button>with anaria-labelandaria-pressedthat reflect the current state:Marquee.create(el, { showPauseButton: true });The button reports the explicit stop, not the aggregate pause — a marquee resting because it is hovered or offscreen still reads as playing, so the control does not flip under the user's cursor.
Keyboard.
keyboard: trueputs the container in the tab order withrole="group", then space toggles and the arrow keys for the current axis nudge bykeyboardStep. Keys are ignored when the event came from a link or form control inside the marquee, so nothing is hijacked.Reduced motion snaps home. When the setting is turned on mid-session the marquee returns to offset 0 rather than freezing wherever it happened to be, which would leave an item clipped at each edge.
How the seamless loop works
- Move the container's children into a flex track sized to its content.
- Append one clone of the whole set, then measure the distance between the
first original and the first clone. That delta is the repeat distance, and
it includes the flex
gapfor free — measuring the items and adding a gap by hand is where most marquees get a visible stutter at the seam. - Tile more clones until the track covers the viewport plus one full set.
- Each frame, advance
offsetbyspeed × dtand wrap it into[0, setSize), then applytranslate3d(-offset, 0, 0).
Because the track always has a full extra set beyond the viewport, the wrap
from setSize - ε back to 0 lands on identical pixels. Both directions use
the same formula; scrolling right just decrements offset and relies on the
wrap being two-sided.
dt is clamped to 50 ms so a backgrounded tab cannot integrate one enormous
frame and teleport the content.
Browser support
Chrome / Edge 88+, Firefox 78+, Safari 14+.
| Feature | If missing |
| --- | --- |
| ResizeObserver | Auto re-measure is skipped; call update() yourself. |
| IntersectionObserver | Offscreen pausing is skipped; tab-visibility pausing still works. |
| matchMedia | Reduced motion is treated as "not requested". |
| inert | Falls back to tabindex="-1" on focusable descendants of clones. |
| CSS mask-image | fadeEdges silently does nothing; everything else works. |
The package ships as ES modules with no build step. For a <script> tag, use
the standalone builds in vanilla/ or jquery/ in the repository root.
Developer
Built by Kenneth D'silva — modracx.com
License
MIT © Kenneth D'silva (Modracx)
