https://github.com/tasxatzial/click-and-hold-button
Click and hold functionality (long press event) using plain JavaScript
https://github.com/tasxatzial/click-and-hold-button
long-press
Last synced: 4 months ago
JSON representation
Click and hold functionality (long press event) using plain JavaScript
- Host: GitHub
- URL: https://github.com/tasxatzial/click-and-hold-button
- Owner: tasxatzial
- License: mit
- Created: 2023-08-08T10:31:40.000Z (almost 2 years ago)
- Default Branch: master
- Last Pushed: 2025-02-28T12:53:03.000Z (4 months ago)
- Last Synced: 2025-02-28T19:08:17.677Z (4 months ago)
- Topics: long-press
- Language: JavaScript
- Homepage: https://tasxatzial.github.io/click-and-hold-button/
- Size: 61.5 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Click-and-hold button
A click-and-hold button is a user interface element that demands users to click on the button and maintain that click for a specific period before the associated action is executed.
This project demonstrates how to add basic click-and-hold functionality to elements using plain JavaScript. Mouse, keyboard, and touch events are supported.
[Live version](https://tasxatzial.github.io/click-and-hold-button/src/index.html)
## Implementation
Two implementations, `animation.js` and `animationFrame.js` are provided.
Both add to the button:
* A `data-click-and-hold` attribute.
* A `--hold-duration` custom CSS property (measured in ms).
* A `data-active-hold` attribute when the hold phase is initiated. The attribute is removed when the hold phase is completed (lasting for at least the specified duration) or cancelled (lasting less than the specified duration).Additionally, `animationFrame.js` adds an extra custom CSS property `--complete-percent` that indicates the elapsed time since the start of the hold phase as a percentage of the hold duration. This number is updated ~X times per second, where X matches the screen refresh rate. For example, a duration of 0.2 seconds and a refresh rate of 60 Hz will give us 0.2 * 60 = ~12 numbers evenly distributed between 0 and ~100.
### Initialization
The user needs to define 3 functions:
* A function that will run when the hold phase starts.
* A function that will run when the hold phase is completed.
* A function that will run when the hold phase is cancelled.### Animations
In both implementations, the animation can be created using either a CSS transition or animation that use the `data-active-hold` property. In `animationFrame.js` the animation can also be created with a CSS transform that uses the `--complete-percent` property.
## Dependencies
None. The project uses only HTML, CSS, JavaScript.
## Use
See [script.js](src/js/script.js), [style.css](src/style.css), [index.html](src/index.html) for a demo use of both implementations.
## Run locally
Download the 'src' folder and use a local web server to serve its contents.