Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/jh3y/use-caret-position
A custom React hook for grabbing the caret position in a text input.
https://github.com/jh3y/use-caret-position
caret dom dom-manipulation hacktoberfest hooks hooks-api-react react reactjs ui ui-components
Last synced: 3 months ago
JSON representation
A custom React hook for grabbing the caret position in a text input.
- Host: GitHub
- URL: https://github.com/jh3y/use-caret-position
- Owner: jh3y
- Created: 2020-10-27T18:43:29.000Z (over 4 years ago)
- Default Branch: main
- Last Pushed: 2022-08-05T03:07:50.000Z (over 2 years ago)
- Last Synced: 2024-10-12T23:45:42.025Z (4 months ago)
- Topics: caret, dom, dom-manipulation, hacktoberfest, hooks, hooks-api-react, react, reactjs, ui, ui-components
- Language: JavaScript
- Homepage: https://use-caret-position.netlify.app/
- Size: 99.6 KB
- Stars: 37
- Watchers: 3
- Forks: 3
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# use-caret-position
A custom React hook for grabbing the caret position in an input field.
## Install
```shell
npm i use-caret-position
``````shell
yarn add use-caret-position
```## Usage
Refer to `src/app/index.js` for common usage examples.
At a high-level, you pass the hook an input ref.
```javascript
import useCaretPosition from 'use-caret-position'
```
```javascript
const { x, y, getPosition, getSelection } = useCaretPosition(inputRef)
```
```javascript
getPosition(inputRef)} />
I'm the marker
```You get an `x` and `y` coordinate that you can use to display a marker with. I'd recommend using CSS variables for this. This is what the demos do. `getPosition` and `getSelection` are functions __you can trigger whenever you need to update__ the `x` and `y` positions.
`getPosition` returns the position at `selectionStart` for an input. `getSelection` returns a midpoint between `selectionStart` and `selectionEnd` for an input. It's tricky to provide an exact accurate `x` and `y` for the caret in all scenarios so often you might need to adjust the positioning slightly with CSS transforms.
## Development
Package is built with `parcel-bundler`. To get to work, use `yarn dev`.
To work with the test app, you'll also need to run `yarn` and `yarn dev` from within `src/app`.
To work with the published node module directly, use `npm link` in the root of the repo.
Then use `npm link use-caret-position` within `src/app`.
---
Made in haste by @jh3y 2020 :sweat_smile: