htmx icon indicating copy to clipboard operation
htmx copied to clipboard

`event` is undefined on `hx-vals` with `delay` modifier on `hx-trigger`

Open jquesada2016 opened this issue 2 years ago • 7 comments

Adding a delay of seemingly any duration, causes the event in hx-vals to be undefined. Take the following example:

<input
  type="text"
  hx-get="/fancy-endpoint"
  hx-trigger="keyup delay:1s"
  hx-vals="js:{ theBug: console.log(event) }">

event is defined if I remove the delay:1s.

jquesada2016 avatar Aug 02 '23 01:08 jquesada2016

This might be related to #1103. Once I remove the delay, if I type too fast, the same error comes up.

jquesada2016 avatar Aug 02 '23 02:08 jquesada2016

I'm curious. Does this happen the same with throttle instead of delay? Throttle sounds like a debounce and should work/feel better for a keyup event where you wouldn’t want a delay at first.

But, sure, this does not fix the bug you describe.

andryyy avatar Aug 02 '23 04:08 andryyy

Reproduction codepen

It's a scope issue; within event handlers, an event object exists automatically on the global scope (window) so Function("{content:event}")() gets the event. But once it is wrapped in a setTimeout, when that Function gets evaluated, the window.event has already been set back to undefined

As such, @andryyy , throttle would have access to the event just fine since it is not wrapped within a timeout

matiboy avatar Aug 02 '23 04:08 matiboy

This error doesn't seem to happen if I use throttle, but it doesn't work in my case either because if the user types too quickly, only the first event is fired, not the other events that happen within the throttle timeout. Also, delay is the modifier used within the example, which is why I went with it originally.

jquesada2016 avatar Aug 02 '23 14:08 jquesada2016

Is it fixed by PR 1460?

wdscxsj avatar Sep 23 '23 15:09 wdscxsj

Is it fixed by #1460?

For me yes. When integrating the changes of #1460, the event object is available, also when a delay is defined.

gulaschsippl avatar Feb 15 '24 16:02 gulaschsippl