Mouse click and hold event (long press) #4242
-
QuestionI'm going to implement an event that triggers when a user clicks and holds a "checkbox." However, JavaScript doesn't seem to have a specific event type for this action. Does anyone know of a workaround to achieve this in NiceGUI? Here is an example from javascript: //Function on mouse down
divRef.addEventListener(events[deviceType].down, (e) => {
e.preventDefault();
isMouseHold = true;
//Mouse down will be considered mouse hold if it is being held down for more than 1500ms
timeoutref = setTimeout(function () {
//If mouse is being held down do this
if (isMouseHold) {
result.innerText = "Mouse is being held down";
}
}, 1500);
}); |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
Here is my first attempt. It works perfectly with a mouse but not with touch events. # hold on event
self.on("mousedown", self._mouse_down_event)
self.on("mouseup", self._mouse_up_event)
async def _mouse_down_event(self):
try:
self._hold = True
await asyncio.sleep(0.3)
if self._hold:
ui.notify("Hold event", color="info")
except Exception as e:
logger.exception("Hold event", e)
finally:
self._hold = False
async def _mouse_up_event(self):
self._hold = False |
Beta Was this translation helpful? Give feedback.
-
Hi @daya0576, To extend your solution to touch events, you can simply subscribe to two more events: hold = False
async def handle_mouse_down():
global hold
hold = True
await asyncio.sleep(0.5)
if hold:
ui.notify("Hold")
async def handle_mouse_up():
global hold
hold = False
ui.button("Hold") \
.on("mousedown", handle_mouse_down) \
.on("mouseup", handle_mouse_up) \
.on("touchstart", handle_mouse_down) \
.on("touchend", handle_mouse_up) There's one catch though: If you repeatedly click the button, there's a good chance a "hold" event will trigger because after sleeping 0.5 seconds release = asyncio.Event()
async def handle_mouse_down():
release.clear()
try:
async with asyncio.timeout(0.5):
await release.wait()
except asyncio.TimeoutError:
ui.notify("Hold")
async def handle_mouse_up():
release.set()
ui.button("Hold") \
.on("mousedown", handle_mouse_down) \
.on("mouseup", handle_mouse_up) \
.on("touchstart", handle_mouse_down) \
.on("touchend", handle_mouse_up) |
Beta Was this translation helpful? Give feedback.
Hi @daya0576,
To extend your solution to touch events, you can simply subscribe to two more events:
There's one catch though: If you repeatedly click the button, there's a good chance a "hold" event will trigger because after sleeping 0.5 seconds
hold
is true again. We should cancel the mouse down handler a…