Git Product home page Git Product logo

debounced's Introduction

Lines of Code Codacy Badge NPM Version NPM Downloads NPM Bundle Size

Debounced

Debounced versions of native DOM events

This library uses event delegation to add debounced versions of native (and custom) bubbling DOM events.

Table of Contents

Why?

Have you ever wired up event listeners for keyup, input, or mousemove? If so, you know that these events are dispatched frequently and often necessitate adding custom debounce functionality to your application.

What if you could simply listen for a debounced event instead? Now you can.

This technique pairs extremely well with libraries like Stimulus, TurboBoost Commands, and StimulusReflex. Here are some examples.

<input type="text" data-controller="example" data-action="debounced:input->example#work">
<input type="text" data-reflex="debounced:input->Example#work">

Install

npm install debounced

Quick Start

Tip

Add the following code to your JavaScript app's entry point. Somwhere like: app/javascript/application.js

Invoking initialize without arguments will register debounced events for all native DOM events that bubble.

import debounced from 'debounced'

// initialize without args to register all native DOM events that bubble
debounced.initialize()

You can also initialize with a custom list of events.

// initialize with a custom list of events
debounced.initialize(['click', 'input', 'keydown'])
// listen for debounced events
document.addEventListener('debounced:input', event => { ... })
document.getElementById('example').addEventListener('debounced:keydown', event => { ... })
document.querySelectorAll('a').forEach(a => {
  a.addEventListener('debounced:click', event => { ... })
})

Usage

Initialize with custom options.

debounced.initialize(debounced.defaultEventNames, { wait: 500, leading: true, trailing: false })

You can register additional events at any time.

// register more events after initialization
debounced.register(['change', 'mousedown'])

You can customize options for registered events by re-registering with different options.

// re-register events and to change options
debounced.register(debounced.registeredEventNames, { wait: 100 })

Leading / Trailing Debounce

You can specify when debounced events fire via the leading and trailing options.

  • leading - fires after the source event but before waiting
  • trailing - fires after the source event and after waiting

Leading and trailing events will only fire once per source event.

Note

If both leading and trailing are true, a debounced event will trigger before and after the timeout.

Custom Events

You can add debounced versions of custom events.

// register an individual custom event
debounced.registerEvent('custom-event', { ... })

// register a list of custom events
debounced.register(['custom-event-one', 'custom-event-two'], { wait: 150 })

Unregistering Events

You can unregiser events at any time.

// unregister a single event
debounced.unregisterEvent('keyup')

// unregister a list of events
debounced.unregister(['click', 'input', 'keydown'])

// unregister all events
debounced.unregister(debounced.registeredEventNames)

Debounced Event Prefix

Important

Setting the prefix needs to be done before invoking initialize or register[Event].

You can change the prefix of the debounced event names.

debounced.prefix = 'custom-prefix' // must be set before invoking initialize
debounced.initialize()
document.addEventListener('custom-prefix:click', event => { ... })

API

Name Description
defaultEventNames List of native DOM events that bubble
defaultOptions Default options applied when registering events
initialize Initializes and registers debounced events
prefix Prefix used for debounced event names (get/set)
registerEvent Registers a single event for debouncing
register Registers a list of events for debouncing
registeredEventNames List of all registered event names
registeredEvents All registered events with their options
unregisterEvent Unregisters a single event
unregister Unregisters a list of events

The source is small and well documented. Learn more about the API here.

FAQ

Q: What are the default native events that bubble?

A: View the list here and learn more about these events at MDN.


Q: Can I register an event more than once?

A: Yes, event re-registration overwrites any existing registrations.


Q: Do I have to specify all options when registering an event?

A: No, any omitted options will apply the defaults.


Q: Are importmaps supported?

A: Yes, this library is compatible with importmaps.

Releasing

  1. Run npm update to pick up the latest dependencies
  2. Update the version at package.json - pre-release versions use -preN
  3. Run npm run standardize
  4. Run npm run build
  5. Commit and push any changes to GitHub
  6. Run npm publish --access public
  7. Create a new release on GitHub (here)

debounced's People

Contributors

davekaro avatar dependabot[bot] avatar hopsoft avatar jsip avatar r4mbo7 avatar x4d3 avatar zajn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

debounced's Issues

Events are ignored if they are triggered at the same time and from the same type

Currently, if two elements, trigger the same event type at the same time, only one will make it to the debounced listener.

It is because they go through the same dispatch channel and the timeoutId may be cleared for the first event.
https://github.com/hopsoft/debounced/blob/master/src/index.js#L10

I've made a minimal reproduction example that can be found here: https://x4d3.github.io/debounced-issue/

https://github.com/x4d3/debounced-issue/blob/main/index.html

`debounced:scroll` on Scrollable Elements

First and foremost, many thanks for the great library – it's a real joy to work with :)

Just thought I'd make a note of one minor hiccup I think I've found when it comes to scrolling on individual elements rather than the document.

Let's say we have an HTML structure along these lines, with elements on the page that are individually scrollable:

<body style="display: flex">
  <nav id="sidebar" style="overflow-y: scroll">
    ...
  </nav>
  <div id="main-pane" style="overflow-y: scroll">
    ...
  </div>
</body>

Here, scrolling on either the sidebar or the main-pane will fire a scroll event on the element in question, but this event will not bubble up to the document as far as I understand.

Because debounced:scroll is ultimately handled via an event listener on the document (this part here), I don’t think it’s currently possible to listen for a debounced scroll on the scrollable elements themselves. This means something like the following will not be fired on scroll:

const sidebar = document.getElementById("sidebar");
sidebar.addEventListener("debounced:scroll", () => console.log("scrolling..."));

If this is the case then I don’t have a neat solution in mind unfortunately – just thought I’d post in here in case someone else might!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.