I create a square div, and I want to know how many pointer is triggering pointer down event in the div on the screen; there is no property like event.touches.length in pointer event, so I use a counter variable to calculate the number of finger down (ie pointer down event) inside the div, and achieve these conditions:
1. Pointer down inside the div, counter plus 1.
3. Pointer down inside the div (counter plus 1), and release pointer inside the div, counter minus 1.
3. Pointer down inside the div (counter plus 1), move outside the div, and release outside the div, counter still minus 1.
4. Pointer down and pointer up outside the div (click outside), counter does nothing.
My program is like this:
var elem, counter,
onDown, onUp,
animate;
counter = 0;
onDown = function () {
var body;
body = document.body;
counter++;
// body.addEventListener('mouseup', onUp, false);
body.addEventListener('pointerup', onUp, false);
};
onUp = function () {
var body;
body = document.body;
counter--;
// body.removeEventListener('mouseup', onUp);
body.removeEventListener('pointerup', onUp);
};
elem = document.getElementById('square');
//elem.addEventListener('mousedown', onDown, false);
elem.addEventListener('pointerdown', onDown, false);
animate = function () {
// Use different color according to the number of fingers
// How many fingers are trigger pointer down inside the div,
// and not released yet.
// (Include the finger which is moved outside after
// pointer down inside the div)
switch (counter) {
case 1:
elem.style.backgroundColor = 'red';
break;
case 2:
elem.style.backgroundColor = 'yellow';
break;
case 3:
elem.style.backgroundColor = 'blue';
break;
case 4:
elem.style.backgroundColor = 'black';
break;
default:
elem.style.backgroundColor = 'white';
}
requestAnimationFrame(animate);
};
animate();
#square {
width: 300px;
height: 300px;
border: 1px solid black;
}
<div id="square"></div>
In general, we only use one mouse, so there is no problem occurred. But there is a problem occurred in pointer event. For example, my index finger of left hand touch down inside the div, the pointer down event is triggered, counter is 1 now; but my index finger of right hand "click" outside the div, pointer up event is triggered here, so my counter get a wrong number 0. (My left index finger is still pressed)
I don't want click event occurred outside of the div (pointerdown and pointerup are both fired outside of the div) to affect my counter.
If there is a way to determine my pointer up event is correlated to which pointer down event?
Just like the event target of touch start event and touch end event is the same, so that I can know they are related.
Thanks in advance.