- I know this is a common question and asked a lot of times but it doesn't seem to work with me i don't know why
- I'm trying to make a counter, function to acting with long press but when i use
mousedown, pointerdown
events and keep pressing on element it doesn't do anything it's acting likeclick
event - i'm trying this on Android phone can anyone help me - What i'm trying to do is increase the counter when user keep press the element
- Here's an example of my code
<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<link rel="stylesheet" href="" type="text/css"/>
<style>
#ok {
background: #03fab3;
padding: 30px;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
touch-action: auto;
}
</style>
</head>
<body>
<div id="ok">0</div>
<script>
var i = 1,
ok = document.getElementById("ok") ;
ok.addEventListener("pointerdown", function (e) {
i ;
this.innerHTML = i " " e.buttons;
});
</script>
</body>
</html>
CodePudding user response:
Mousedown simply checks whether the click event started. Until you se "mouseup" event, you need to create a "Setinterval" and increase your variable depending on time.
So looking "mousedown" event is just acts like "click" event of the browser without additional controls.
CodePudding user response:
pointerdown
/mousedown
events do not fire continuously while the button is held. So, you'll need detect two events: when button was pressed and when it was released.
var i = 0,
el, //this will hold clicked element
buttons = false,
lastTimer = 0,
onPointerEvent = e => buttons = e.buttons; //store pressed buttons in a variable
ok.addEventListener("pointerdown", function (e)
{
el = e.target;
onPointerEvent(e);
i = 0; //reset counter
counter(); //start the counter
}, true);
window.addEventListener("pointerup", onPointerEvent); //non-touch devices
window.addEventListener("pointercancel", onPointerEvent); //touch devices
function counter(timer)
{
if (!buttons) //exit loop when button released
return;
if (timer >= lastTimer 10) //update counter every 10ms
{
lastTimer = timer;
el.textContent = i " " buttons;
}
requestAnimationFrame(counter); //create loop
}
#ok > *{
background: #03fab3;
padding: 30px;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
touch-action: auto;
margin: 1px;
}
<div id="ok">
<div>0</div>
<div>0</div>
<div>0</div>
</div>