Posts Learn Components Snippets Categories Tags About

Vue Js Long Press Directive

Learn how to define long press directive in Vue Js

Created on Sep 11, 2021


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>
The directive will be as follows.
const PRESS_TIMEOUT = 1000;

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

    let pressTimer = null;

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

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

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

    ;["mousedown", "touchstart"].forEach(e => el.addEventListener(e, start));
    ;["click", "mouseout", "touchend", "touchcancel"].forEach(e => el.addEventListener(e, cancel));

Snippets by

PostSrc poster


Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

Load comments for Vue Js Long Press Directive


PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your project.

View Components

Other Code Snippets