Events

Introduction

Yew integrates with the web-sys crate and uses the events from that crate. The table below lists all of the web-sys events that are accepted in the html! macro.

You can still add a Callback for an event that is not listed in the table below, see Manual event listener.

Event Types

Events - 图1提示

All the event types mentioned in the following table are re-exported under yew::events. Using the types from yew::events makes it easier to ensure version compatibility than if you were to manually include web-sys as a dependency in your crate because you won’t end up using a version which conflicts with the version that Yew specifies.

The event listener name is the expected name when adding an event Callback in the html macro:

  1. use yew::{html, Callback};
  2. html! {
  3. <button onclick={Callback::from(|_| ())}>
  4. // ^^^^^^^ event listener name
  5. { "Click me!" }
  6. </button>
  7. };

The event name is the listener without the “on” prefix, therefore, the onclick event listener listens for click events.

Event listener nameweb_sys Event Typestdweb Event Type
onabortEventResourceAbortEvent
onauxclickMouseEventAuxClickEvent
onblurFocusEventBlurEvent
oncancelEventUnsupported
oncanplayEventUnsupported
oncanplaythroughEventUnsupported
onchangeChangeDataChangeData
onclickMouseEventClickEvent
oncloseEventUnsupported
oncontextmenuMouseEventContextMenuEvent
oncuechangeEventUnsupported
ondblclickMouseEventDoubleClickEvent
ondragDragEventDragEvent
ondragendDragEventDragEndEvent
ondragenterDragEventDragEnterEvent
ondragexitDragEventDragExitEvent
ondragleaveDragEventDragLeaveEvent
ondragoverDragEventDragOverEvent
ondragstartDragEventDragStartEvent
ondropDragEventDragDropEvent
ondurationchangeEventUnsupported
onemptiedEventUnsupported
onendedEventUnsupported
onerrorEventResourceErrorEvent
onfocusFocusEventFocusEvent
onformdataEventUnsupported
oninputInputDataInputData
oninvalidEventUnsupported
onkeydownKeyboardEventKeyDownEvent
onkeypressKeyboardEventKeyPressEvent
onkeyupKeyboardEventKeyUpEvent
onloadEventResourceLoadEvent
onloadeddataEventUnsupported
onloadedmetadataEventUnsupported
onloadstartProgressEventLoadStartEvent
onmousedownMouseEventMouseDownEvent
onmouseenterMouseEventMouseEnterEvent
onmouseleaveMouseEventMouseLeaveEvent
onmousemoveMouseEventMouseMoveEvent
onmouseoutMouseEventMouseOutEvent
onmouseoverMouseEventMouseOverEvent
onmouseupMouseEventMouseUpEvent
onpauseEventUnsupported
onplayEventUnsupported
onplayingEventUnsupported
onprogressProgressEventProgressEvent
onratechangeEventUnsupported
onresetEventUnsupported
onresizeEventResizeEvent
onscrollEventScrollEvent
onsecuritypolicyviolationEventUnsupported
onseekedEventUnsupported
onseekingEventUnsupported
onselectEventUnsupported
onslotchangeEventSlotChangeEvent
onstalledEventUnsupported
onsubmitFocusEventSubmitEvent
onsuspendEventUnsupported
ontimeupdateEventUnsupported
ontoggleEventUnsupported
onvolumechangeEventUnsupported
onwaitingEventUnsupported
onwheelWheelEventMouseWheelEvent
oncopyEventUnsupported
oncutEventUnsupported
onpasteEventUnsupported
onanimationcancelAnimationEventUnsupported
onanimationendAnimationEventUnsupported
onanimationiterationAnimationEventUnsupported
onanimationstartAnimationEventUnsupported
ongotpointercapturePointerEventGotPointerCaptureEvent
onloadendProgressEventLoadEndEvent
onlostpointercapturePointerEventLostPointerCaptureEvent
onpointercancelPointerEventPointerCancelEvent
onpointerdownPointerEventPointerDownEvent
onpointerenterPointerEventPointerEnterEvent
onpointerleavePointerEventPointerLeaveEvent
onpointerlockchangeEventPointerLockChangeEvent
onpointerlockerrorEventPointerLockErrorEvent
onpointermovePointerEventPointerMoveEvent
onpointeroutPointerEventPointerOutEvent
onpointeroverPointerEventPointerOverEvent
onpointerupPointerEventPointerUpEvent
onselectionchangeEventSelectionChangeEvent
onselectstartEventUnsupported
onshowEventUnsupported
ontouchcancelTouchEventTouchCancel
ontouchendTouchEventTouchEnd
ontouchmoveTouchEventTouchMove
ontouchstartTouchEventTouchStart
ontransitioncancelTransitionEventUnsupported
ontransitionendTransitionEventUnsupported
ontransitionrunTransitionEventUnsupported
ontransitionstartTransitionEventUnsupported

oninput and onchange

Events - 图2备注

In the next version of Yew oninput and onchange Callbacks will accept InputEvent and Event respectively.

Yew will be removing InputData and ChangeData as they were too restrictive and could panic in certain circumstances.

Events - 图3警告

You must apply the Callback to the target element even though the InputEvent/Event bubbles up, the InputData/ChangeData is expecting the “target” to also be the “currentTarget” (see the caution in Typed event target section for more).

DO NOT DO THIS

  1. use yew::{html, ChangeData, Html, InputData};
  2. enum Msg {
  3. InputValue(String),
  4. }
  5. fn view(&self) -> Html {
  6. let oninput = self.link.callback(|e: InputData| Msg::InputValue(e.value));
  7. let onchange = self.link.batch_callback(|e: ChangeData| {
  8. if let ChangeData::Value(value) = e {
  9. Some(Msg::InputValue(value))
  10. } else {
  11. None
  12. }
  13. });
  14. html! {
  15. <div
  16. // The `InputEvent` can bubble and then will read the text content
  17. // of the div as the value in `InputData` which is not what you'd
  18. // expect!
  19. oninput={oninput}
  20. // The `Event` can bubble and will cause a panic when it tries
  21. // to create the `ChangeData` enum.
  22. onchange={onchange}
  23. >
  24. { "hi" }
  25. <input type="text" />
  26. </div>
  27. }
  28. }

oninput using InputData

Yew wraps the InputEvent in an InputData type, the InputData type also contains the current value of the element on which the oninput handler is applied.

Yew does this by trying to cast the element into an input or textarea element then calling their respective value getter method or it will get the text content of the element.

  1. use yew::{html, Html, InputData};
  2. enum Msg {
  3. InputValue(String),
  4. }
  5. fn view(&self) -> Html {
  6. let oninput = self.link.callback(|e: InputData| Msg::InputValue(e.value));
  7. html! {
  8. <div>
  9. <input oninput={oninput} />
  10. </div>
  11. }
  12. }

If you want to get the value as a number (f64) then InputData does have the event field which is the web_sys::InputEvent that you can use with the information provided in the Typed event target section and then you can call value_as_number method on the target.

onchange using ChangeData

The ChangeData type is an enum which has a variant for the three supported element types:

Variant nameVariant data typeElement type
Filesweb_sys::FileListinput with type of file
Selectweb_sys::HtmlSelectElementselect element
ValueStringtextarea or input with any type other than file

If onchange is used on any other element then the application will panic when Yew tries to convert the Event into ChangeData.

Files

When a user has made a change to the files selected by an input element with the type file.

  1. use yew::{html, Html, ChangeData};
  2. fn view(&self) -> Html {
  3. let onchange = self.link.batch_callback(|e| {
  4. if let ChangeData::Files(files) = e {
  5. // do something with web_sys::FileList
  6. } else {
  7. None
  8. }
  9. });
  10. html! {
  11. <div>
  12. <input onchange={onchange} type="file" />
  13. </div>
  14. }
  15. }

Events - 图4提示

Use batch_callback when you want to conditionally return a value from a Callback.

see file_upload for a full example.

Select

When a user has made a change to the select element.

  1. use yew::{html, Html, ChangeData};
  2. fn view(&self) -> Html {
  3. let onchange = self.link.batch_callback(|e| {
  4. if let ChangeData::Select(select) = e {
  5. // do something with web_sys::HtmlSelectElement
  6. } else {
  7. None
  8. }
  9. });
  10. html! {
  11. <div>
  12. <select onchange={onchange}>
  13. <option value="English">{ "Hello!" }</option>
  14. <option value="French">{ "Bonjour!" }</option>
  15. <option value="German">{ "Guten Tag!" }</option>
  16. </select>
  17. </div>
  18. }
  19. }

Value

When a user has made a change to a textarea or input element with any type other than file.

  1. use yew::{html, Html, ChangeData};
  2. fn view(&self) -> Html {
  3. let onchange = self.link.batch_callback(|e| {
  4. if let ChangeData::Value(value) = e {
  5. // do something with the String value
  6. } else {
  7. None
  8. }
  9. });
  10. html! {
  11. <div>
  12. <textarea onchange={onchange} />
  13. </div>
  14. }
  15. }

see crm for a full example.

Typed event target

Events - 图5警告

In this section target (Event.target) is always referring to the element at which the event was dispatched from.

This will not always be the element at which the Callback is placed, that is the Event.currentTarget

In event Callbacks you may want to get the target of that event. For example, on the input event you may want to update some internal state.

In Yew getting the target element in the correct type can be done in a couple of ways and we will go through them here. Calling web_sys::Event::target on an event returns an optional web_sys::EventTarget type, which might not seem very useful when you want to know the value of your input element.

In all the approaches below we are going to tackle the same problem, so it’s clear where the approach differs opposed to the problem at hand.

The Problem:

We have an oninput Callback on my <input> element and each time it is invoked we want to send an update Msg to our component. We really want to get the value as a number or f64 for rust.

Our Msg enum looks like this:

  1. pub enum Msg {
  2. InputValue(f64),
  3. }

Using JsCast

The wasm-bindgen crate has a useful trait; JsCast which allows us to hop and skip our way to the type we want, as long as it implements JsCast. We can do this cautiously, which involves some runtime checks and failure types like Option and Result, or we can do it dangerously.

Enough talk, more code:

Cargo.toml

  1. [dependencies]
  2. # need wasm-bindgen for JsCast
  3. wasm-bindgen = "0.2"
  1. use wasm_bindgen::JsCast;
  2. use yew::{
  3. html,
  4. web_sys::{EventTarget, HtmlInputElement},
  5. Component, ComponentLink, Html, InputData,
  6. };
  7. pub struct Comp {
  8. link: ComponentLink<Self>,
  9. }
  10. pub enum Msg {
  11. InputValue(f64),
  12. }
  13. impl Component for Comp {
  14. type Message = Msg;
  15. type Properties = ();
  16. fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
  17. Self { link }
  18. }
  19. fn update(&mut self, msg: Self::Message) -> yew::ShouldRender {
  20. let Msg::InputValue(value) = msg;
  21. // do something with value
  22. todo!()
  23. }
  24. fn change(&mut self, _props: Self::Properties) -> yew::ShouldRender {
  25. false
  26. }
  27. fn view(&self) -> Html {
  28. let link = &self.link;
  29. // Use batch_callback so if something unexpected happens we can return
  30. // None and do nothing
  31. let on_cautious_change = link.batch_callback(|e: InputData| {
  32. let e = e.event;
  33. // When events are created the target is undefined, it's only
  34. // when dispatched does the target get added.
  35. let target: Option<EventTarget> = e.target();
  36. // Events can bubble so this listener might catch events from child
  37. // elements which are not of type HtmlInputElement
  38. let input = target.and_then(|t| t.dyn_into::<HtmlInputElement>().ok());
  39. input.map(|input| Msg::InputValue(input.value_as_number()))
  40. });
  41. let on_dangerous_change = link.callback(|e: InputData| {
  42. let e = e.event;
  43. let target: EventTarget = e
  44. .target()
  45. .expect("Event should have a target when dispatched");
  46. // You must KNOW target is a HtmlInputElement, otherwise
  47. // the call to value would be Undefined Behaviour (UB).
  48. Msg::InputValue(
  49. target
  50. .unchecked_into::<HtmlInputElement>()
  51. .value_as_number(),
  52. )
  53. });
  54. html! {
  55. <>
  56. <label for="cautious-input">
  57. { "My cautious input:" }
  58. <input oninput={on_cautious_change}
  59. id="cautious-input"
  60. type="text"
  61. />
  62. </label>
  63. <label for="dangerous-input">
  64. { "My dangerous input:" }
  65. <input oninput={on_dangerous_change}
  66. id="dangerous-input"
  67. type="text"
  68. />
  69. </label>
  70. </>
  71. }
  72. }
  73. }

Events - 图6提示

Use batch_callback when you want to conditionally return a value from a Callback.

The methods from JsCast are dyn_into and unchecked_into and you can probably see, they allowed us to go from EventTarget to HtmlInputElement. The dyn_into method is cautious because at runtime it will check whether the type is actually a HtmlInputElement and if not return an Err(JsValue), the JsValue is a catch-all type and is essentially giving you back the object to try again.

At this point you might be thinking… when is the dangerous version ok to use? In the case above it is safe1 as we’ve set the Callback on to an element with no children so the target can only be that same element.

1 As safe as anything can be when JS land is involved.

Using NodeRef

NodeRef can be used instead of querying the event given to a Callback.

  1. use yew::{html, web_sys::HtmlInputElement, Component, ComponentLink, Html, NodeRef};
  2. pub struct Comp {
  3. link: ComponentLink<Self>,
  4. my_input: NodeRef,
  5. }
  6. pub enum Msg {
  7. InputValue(f64),
  8. }
  9. impl Component for Comp {
  10. type Message = Msg;
  11. type Properties = ();
  12. fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
  13. Self {
  14. link,
  15. my_input: NodeRef::default(),
  16. }
  17. }
  18. fn update(&mut self, msg: Self::Message) -> yew::ShouldRender {
  19. let Msg::InputValue(value) = msg;
  20. // do something with value
  21. todo!()
  22. }
  23. fn change(&mut self, _props: Self::Properties) -> yew::ShouldRender {
  24. false
  25. }
  26. fn view(&self) -> Html {
  27. let my_input_ref = self.my_input.clone();
  28. let oninput = self.link.batch_callback(move |_| {
  29. let input = my_input_ref.cast::<HtmlInputElement>();
  30. input.map(|input| Msg::InputValue(input.value_as_number()))
  31. });
  32. html! {
  33. <>
  34. <label for="my-input">
  35. { "My input:" }
  36. <input ref={self.my_input.clone()}
  37. oninput={oninput}
  38. id="my-input"
  39. type="text"
  40. />
  41. </label>
  42. </>
  43. }
  44. }
  45. }

Using NodeRef, you can ignore the event and use the NodeRef::cast method to get an Option<HtmlInputElement> - this is optional as calling cast before the NodeRef has been set, or when the type doesn’t match will return None.

You might also see by using NodeRef we don’t have to send the f64 back in the Msg::InputValue as we always have my_input in the component state - so we could do the following:

  1. use yew::{html, web_sys::HtmlInputElement, Component, ComponentLink, Html, NodeRef};
  2. pub struct Comp {
  3. link: ComponentLink<Self>,
  4. my_input: NodeRef,
  5. }
  6. pub enum Msg {
  7. // Signal the input element has changed
  8. InputChanged,
  9. }
  10. impl Component for Comp {
  11. type Message = Msg;
  12. type Properties = ();
  13. fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
  14. Self {
  15. link,
  16. my_input: NodeRef::default(),
  17. }
  18. }
  19. fn change(&mut self, _props: Self::Properties) -> yew::ShouldRender {
  20. false
  21. }
  22. fn update(&mut self, msg: Self::Message) -> bool {
  23. match msg {
  24. Msg::InputChanged => {
  25. if let Some(input) = self.my_input.cast::<HtmlInputElement>() {
  26. let value = input.value_as_number();
  27. // do something with value
  28. true
  29. } else {
  30. false
  31. }
  32. }
  33. }
  34. }
  35. fn view(&self) -> Html {
  36. let oninput = self.link.callback(|_| Msg::InputChanged);
  37. html! {
  38. <label for="my-input">
  39. { "My input:" }
  40. <input ref={self.my_input.clone()}
  41. oninput={oninput}
  42. id="my-input"
  43. type="text"
  44. />
  45. </label>
  46. }
  47. }
  48. }

Which approach you take depends on your component and your preferences, there is no blessed way per se.

Manual event listener

You may want to listen to an event that is not supported by Yew’s html macro, see the supported events listed here.

In order to add an event listener to one of elements manually we need the help of NodeRef so that in the rendered method we can add a listener using the web-sys and wasm-bindgen API. We do this in rendered as this is the only time we can guarantee that the element exists in the browser, Yew needs some time to create them after view is called.

The examples below are going to show adding listeners for the made-up custard event. All events either unsupported by yew or custom can be represented as a web_sys::Event. If you need to access a specific method or field on a custom / unsupported event then you can use the methods of JsCast in order to convert to the type required.

Using Closure (verbose)

Using the web-sys and wasm-bindgen API’s directly for this can be a bit painful.. so brace yourself (there is a more concise way thanks to gloo).

  1. use wasm_bindgen::{prelude::Closure, JsCast};
  2. use yew::{
  3. html,
  4. web_sys::{Event, HtmlElement},
  5. Component, ComponentLink, Html, NodeRef,
  6. };
  7. pub struct Comp {
  8. link: ComponentLink<Self>,
  9. my_div: NodeRef,
  10. custard_listener: Option<Closure<dyn Fn(Event)>>,
  11. }
  12. pub enum Msg {
  13. Custard,
  14. }
  15. impl Component for Comp {
  16. type Message = Msg;
  17. type Properties = ();
  18. fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
  19. Self {
  20. link,
  21. my_div: NodeRef::default(),
  22. custard_listener: None,
  23. }
  24. }
  25. fn update(&mut self, msg: Self::Message) -> bool {
  26. match msg {
  27. Msg::Custard => {
  28. // do something about custard..
  29. true
  30. }
  31. }
  32. }
  33. fn change(&mut self, _props: Self::Properties) -> yew::ShouldRender {
  34. false
  35. }
  36. fn view(&self) -> Html {
  37. html! {
  38. <div ref={self.my_div.clone()} id="my-div"></div>
  39. }
  40. }
  41. fn rendered(&mut self, first_render: bool) {
  42. if !first_render {
  43. return;
  44. }
  45. if let Some(element) = self.my_div.cast::<HtmlElement>() {
  46. // Create your Callback as you normally would
  47. let oncustard = self.link.callback(|_: Event| Msg::Custard);
  48. // Create a Closure from a Box<dyn Fn> - this has to be 'static
  49. let listener =
  50. Closure::<dyn Fn(Event)>::wrap(
  51. Box::new(move |e: Event| oncustard.emit(e))
  52. );
  53. element
  54. .add_event_listener_with_callback(
  55. "custard",
  56. listener.as_ref().unchecked_ref()
  57. )
  58. .unwrap();
  59. // Need to save listener in the component otherwise when the
  60. // event is fired it will try and call the listener that no longer
  61. // exists in memory!
  62. self.custard_listener = Some(listener);
  63. }
  64. }
  65. fn destroy(&mut self) {
  66. // All done with the component but need to remove
  67. // the event listener before the custard_listener memory
  68. // goes out of scope.
  69. if let (Some(element), Some(listener)) = (
  70. self.my_div.cast::<HtmlElement>(),
  71. self.custard_listener.take(),
  72. ) {
  73. element
  74. .remove_event_listener_with_callback(
  75. "custard",
  76. listener.as_ref().unchecked_ref()
  77. )
  78. .unwrap();
  79. }
  80. }
  81. }

For more information on Closures, see The wasm-bindgen Guide.

Using gloo (concise)

The easier way is with gloo, more specifically gloo_events which is an abstraction for web-sys, wasm-bindgen.

gloo_events has the EventListener type which can be used to create and store the event listener.

Cargo.toml

  1. [dependencies]
  2. gloo-events = "0.1"
  1. use yew::{
  2. html,
  3. web_sys::{Event, HtmlElement},
  4. Component, ComponentLink, Html, NodeRef,
  5. };
  6. use gloo::events::EventListener;
  7. pub struct Comp {
  8. link: ComponentLink<Self>,
  9. my_div: NodeRef,
  10. custard_listener: Option<EventListener>,
  11. }
  12. pub enum Msg {
  13. Custard,
  14. }
  15. impl Component for Comp {
  16. type Message = Msg;
  17. type Properties = ();
  18. fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
  19. Self {
  20. link,
  21. my_div: NodeRef::default(),
  22. custard_listener: None,
  23. }
  24. }
  25. fn update(&mut self, msg: Self::Message) -> bool {
  26. match msg {
  27. Msg::Custard => {
  28. // do something about custard..
  29. true
  30. }
  31. }
  32. }
  33. fn change(&mut self, _props: Self::Properties) -> yew::ShouldRender {
  34. false
  35. }
  36. fn view(&self) -> Html {
  37. html! {
  38. <div ref={self.my_div.clone()} id="my-div"></div>
  39. }
  40. }
  41. fn rendered(&mut self, first_render: bool) {
  42. if !first_render {
  43. return;
  44. }
  45. if let Some(element) = self.my_div.cast::<HtmlElement>() {
  46. // Create your Callback as you normally would
  47. let oncustard = self.link.callback(|_: Event| Msg::Custard);
  48. let listener =
  49. EventListener::new(
  50. &element,
  51. "custard",
  52. move |e| oncustard.emit(e.clone())
  53. );
  54. self.custard_listener = Some(listener);
  55. }
  56. }
  57. }

Notice that when using an EventListener you don’t need to do anything when the component is about to be destroyed as the EventListener has a drop implementation which will remove the event listener from the element.

For more information on EventListener, see the gloo_events docs.rs.