This is JavaScript library for tracking selection changes in the page, we will using this for create wysiwyg editor or page builder.
For track selection library use
Range API,
Selection API
and listen selectionchange
and pointerdown
events
Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | ? |
npm install selection-observer
Listen all selection changes:
import { SelectionObserver } from 'selection-observer';
const observer = new SelectionObserver((entry) => {
console.log(entry);
});
observer.observe(document.body);
Listen only base element changes:
import { SelectionObserver } from 'selection-observer';
const observer = new SelectionObserver((entry) => {
console.log(entry);
});
observer.observe(document.body, {
onlyElements: true,
});
SelectionObserver interface:
interface SelectionObserver {
constructor(callback: (entry: SelectionObserverEntry) => void);
observe(target: Element, options?: SelectionObserverObserveOptions): void;
disconnect(target: Element): void;
unselectHandler(callback: ({ target: Element, oldTarget: Element }) => void): void;
}
SelectionObserverEntry interface:
interface SelectionObserverEntry {
target: Element;
tag: string;
type: 'layer' | 'title' | 'list' | 'list-item' | 'line' | 'image' | 'paragraph' | 'code' | string;
selection: Selection;
range: Range;
getSelectedNodes: () => Node[];
}
SelectionObserverObserveOptions interface:
interface SelectionObserverObserveOptions {
filter: (item: Element) => boolean;
ignoreMainContainer: boolean;
onlyElements: boolean;
}