Easily observe states of HTML elements and the viewport.
npm install --save @smoovy/observer
Operations like window.innerWidth
and element.offsetTop
will have an impact on the performance if not used properly. So this package is useful to avoid layout thrashing by batching all of the expensive calls together and only executing them if needed.
The observer is separated into two main components. The ViewportObserver
and the ElementObserver
.
import { ViewportObserver } from '@smoovy/observer';
const listener = ViewportObserver.changed(state => {
console.log(`The viewport size is ${state.width}x${state.height}`);
});
To remove the listener you can simply call the remove
method:
listener.remove();
The viewport observer's target is always the current
window
object
This will throttle the changed callback to 100ms:
ViewportObserver.changed((state) => {}, 100);
ViewportObserver.update();
const state = await ViewportObserver.state;
The change gets called everytime the user triggers the resize
event on the window
element. The ViewportObserver
also makes sure to emit only on the next animation frame.
By observing an element you automatically create a state inside the ElementObserver
. This will be your reference to the current state of the element:
import { ElementObserver } from '@smoovy/observer';
const element = document.querySelector('#test');
const state = ElementObserver.observe(element);
const listener = state.changed(state => {
console.log('The element: ', state.element);
console.log('Element size: ', state.size);
console.log('Element page offset: ', state.offset);
});
// Stop listening
listener.remove();
Changes occur when the
ViewportObserver
changes or theMutationObserver
detects changes inside thedocument.documentElement
This will throttle the changed callback to 100ms:
state.changed((state) => {}, 100);
state.update();
state.destroy();
Currently there is a circular dependency warning. This will be fixed in the future, but it shouldn't affect the API.
// Serve with parcel
npm run serve
// Build with rollup
npm run build
// Run Jest unit tests
npm run test
// Run TSLinter
npm run lint
See the LICENSE file for license rights and limitations (MIT).