最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How to apply long click event and doubleclick event on the same element in javascript - Stack Overflow

programmeradmin0浏览0评论

I have an element(textArea). Now I would like a long press event and a double click event on the element. I am able to do this but I would also like to use event.preventDefault() in the mousedown event of long press event. This in turn prevents the dblClick event also.

The reason why I want to preventDefault is I am rendering an element on longPress and wanted to prevent the initial mouseDown as I am firing mousemove after longpress. I have searched and re-searched the net but am unable to find a good answer which solves the problem of long press and dblclick on the same element.

thanks!!

I have an element(textArea). Now I would like a long press event and a double click event on the element. I am able to do this but I would also like to use event.preventDefault() in the mousedown event of long press event. This in turn prevents the dblClick event also.

The reason why I want to preventDefault is I am rendering an element on longPress and wanted to prevent the initial mouseDown as I am firing mousemove after longpress. I have searched and re-searched the net but am unable to find a good answer which solves the problem of long press and dblclick on the same element.

thanks!!

Share Improve this question asked Oct 23, 2013 at 10:36 theRevtheRev 1091 gold badge2 silver badges12 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

Try out this JSFiddle Demo

HTML

<p>
Try it out on this button input:<br><br>
<input type="button" onmousedown="start(event)" onmouseup="revert()" ondblclick="someFun()" value="hold click for awhile">
</p>
<p>
p.s. This solution also works for non-input elements, e.g. a span or div:
<div onmousedown="start(event)" onmouseup="revert()" ondblclick="someFun()" style="border: 2px solid #ff0000;">It also works on this div!</div>
</p>

JavaScript

const delay = 1500; // Duration in milliseconds of how long you have to hold click.
let isActive = false;
let timer;

function start(e) {
  isActive = true;
  timer = setTimeout(makeChange, delay);
  // In case you want to prevent Default functionality on mouse down.
  if (e.preventDefault)  {
    e.preventDefault();
  } else {
    e.returnValue = false; 
  }
}

function makeChange() {
  if (timer) {
    clearTimeout(timer);
  }
  if (isActive) {
    // .. rest of your code here ..
    alert('long click detected');
  }
}

function revert() {
  isActive = false;
}

function someFun() {
  alert('doubleclick detected');
}
发布评论

评论列表(0)

  1. 暂无评论