Reputation: 890
For a Box2D composition, I need this code to avoid unintentional clicks:
(() => {
let lock = 0;
const prevent = e => {
if (lock !== 2)
return;
e.preventDefault();
e.stopPropagation();
};
const unlock = e => {
prevent(e);
setTimeout(() => lock = 0);
};
addEventListener('click', prevent, true);
addEventListener('pointerdown', e => lock = 1, true);
addEventListener('pointermove', e => lock && (lock = 2), true);
addEventListener('pointerup', unlock, true);
addEventListener('pointercancel', unlock, true);
})();
#physics {
width: 300px;
height: 300px;
background-color: blue;
}
<div id="physics"></div>
Currently, it works for the whole document. But I would like to have it for the <div id="physics"></div>
only.
How is it possible to code that?
Would be very thankful for help!
Upvotes: 1
Views: 79
Reputation: 1269
You need to select the div first and then add the handler to that div:
let div = document.getElementById('physics');
div.addEventListener('click', prevent, true);
div.addEventListener('pointerdown', e => lock = 1, true);
div.addEventListener('pointermove', e => lock && (lock = 2), true);
div.addEventListener('pointerup', unlock, true);
div.addEventListener('pointercancel', unlock, true);
Upvotes: 2
Reputation: 402
try
document.getElementById('physics').addEventListener('click', ...);
Upvotes: 1