AddEventListener on Dom.element


#1

Hello everyone,
I’m new to the ReasonML world and
I’m trying to add an EventListener on a Dom.element

open Webapi.Dom;

let item = document |> Document.querySelector(".item");

let handleClick = (_) => Js.log("click");

Document.addEventListener("click", handleClick, item);

but I have an error for the type of the item variable

Error: This expression has type option(Dom.element)
       but an expression was expected of type
         Webapi.Dom.Document.t =
           Dom.eventTarget_like(Dom._node(Dom._document(Dom._baseClass)))

But I didn’t find any solution, so if you know how to do that with ReasonML,
I would be happy to know the answer.


#2

There are two issues with your code:

  • Document.querySelector returns an option
  • Correct addEventListener function for Dom.element is under Webapi.Dom.Element.addEventListener

Fixing these two issues, your code becomes

open Webapi.Dom;

let handleClick = _ => Js.log("click");

switch (document |> Document.querySelector(".item")) {
| Some(el) => el |> Element.addEventListener("click", handleClick)
| None => /* handle element not found */ ()
};

#3

Thanks for you answer.

It works perfectly now !