作成日:2024-04-22, 更新日:2024-04-22
サンプル
<div id="myElement">長押しさせたい要素</div>
<script>
class LongPress {
constructor(element, options = {}) {
this.element = element;
this.eventName = options.eventName || 'longpress'; // イベント名
this.longPressTime = options.longPressTime || 500; // 長押しの条件(ミリ秒)
this.enableClick = options.enableClick || false; // クリックによる長押しを有効にするか
this.timer = null;
this.deviceType = 'touch';
if (!('ontouchstart' in window)) { // タッチイベント未サポートのとき
this.deviceType = 'mouse';
}
this.initEvents();
}
initEvents() {
if (this.deviceType === 'touch') {
this.element.addEventListener('touchstart', (e) => this.startTimer(e), false);
this.element.addEventListener('touchend', (e) => this.clearTimer(e), false);
this.element.addEventListener('touchcancel', (e) => this.clearTimer(e), false);
}
else if (this.deviceType === 'mouse' && this.enableClick) {
this.element.addEventListener('mousedown', (e) => this.startTimer(e), false);
this.element.addEventListener('mouseup', (e) => this.clearTimer(e), false);
this.element.addEventListener('mouseleave', (e) => this.clearTimer(e), false);
}
}
startTimer(event) {
this.timer = setTimeout(() => this.fireLongPress(event), this.longPressTime);
}
clearTimer(event) {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
}
fireLongPress(event) {
const longPressEvent = new CustomEvent(this.eventName, {
bubbles: true, // イベントがバブリングするか
cancelable: true, // イベントがキャンセル可能か
detail: { // カスタムデータ
message: 'Long press detected!'
}
});
this.element.dispatchEvent(longPressEvent);
}
}
// カスタムイベントのイベント名
const evName = 'longpress';
// カスタムイベントの作成
const myElement = document.querySelector('#myElement');
const longPressInstance = new LongPress(myElement, {
eventName: evName,
longPressTime: 500,
enableClick: true, // フラグ: 「(PCの場合)クリックで長押し」を有効
});
// カスタムイベントの登録
myElement.addEventListener(evName, (ev) => {
alert(ev.detail.message);
});
</script>