Home / Snippets / Vue Js Long Press Directive
Vue Js Long Press Directive cover

Vue Js Long Press Directive

226

3 years ago

0 comments

A simple directive to execute a function when the element is long-pressed.
<div id="app">
  <button v-longpress="showOptions">Hold me for a while</button>
</div>
The directive will be as follows.
<script>
const PRESS_TIMEOUT = 1000;

Vue.directive("longpress", {
  bind: function (el, { value }, vNode) {
    if (typeof value !== "function") {
      console.warn(`Expect a function, got ${value}`);
      return;
    }

    let pressTimer = null;

    const start = e => {
      if (e.type === "click" && e.button !== 0) {
        return;
      }

      if (pressTimer === null) {
        pressTimer = setTimeout(() => value(e), PRESS_TIMEOUT);
      }
    }

    const cancel = () => {
      if (pressTimer !== null) {
        clearTimeout(pressTimer);
        pressTimer = null;
      }
    }

    ;["mousedown", "touchstart"].forEach(e => el.addEventListener(e, start));
    ;["click", "mouseout", "touchend", "touchcancel"].forEach(e => el.addEventListener(e, cancel));
  }
})
</script>
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this