Skip to content

Instantly share code, notes, and snippets.

@rowan-m
Created August 27, 2019 09:15
Show Gist options
  • Save rowan-m/81783725a45aa330a043914ace8fe723 to your computer and use it in GitHub Desktop.
Save rowan-m/81783725a45aa330a043914ace8fe723 to your computer and use it in GitHub Desktop.
class InputKnob extends HTMLElement {
// ✂️ existing code has been removed
constructor() {
// Capture the pointer so that the user can still rotate the element even
// if they leave the bounding area of it.
this.setPointerCapture(e.pointerId);
// Re-bind this for listeners so that this == instance of this class
this._onPointerdown = this._onPointerdown.bind(this);
this._onPointermove = this._onPointermove.bind(this);
this._onPointerup = this._onPointerup.bind(this);
}
connectedCallback() {
// Listen for pointerdown events when the element is connected to the page
this.addEventListener('pointerdown', this._onPointerdown);
}
disconnectedCallback() {
// And stop listening if the element is removed
this.removeEventListener('pointerdown', this._onPointerdown);
}
_onPointerdown(e) {
e.preventDefault();
// A long press can bring up the context menu, we want to disable that when
// the user is controlling the element
window.oncontextmenu = () => { return false; };
// Only add listeners for the other events once interaction has started
this.addEventListener('pointermove', this._onPointermove);
this.addEventListener('pointerup', this._onPointerup);
this.addEventListener('pointercancel', this._onPointerup);
}
_onPointermove(e) {
// On all of these we're preventing the default behaviour as we assume our
// web developer won't do something like put a <button> inside the element.
e.preventDefault();
}
_onPointerup(e) {
e.preventDefault();
// Re-enable the context menu
window.oncontextmenu = null;
// Release the pointer we captured earlier
this.releasePointerCapture(e.pointerId);
// Remove all our listeners
this.removeEventListener('pointermove', this._onPointermove);
this.removeEventListener('pointerup', this._onPointerup);
this.removeEventListener('pointercancel', this._onPointerup);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment