Search code examples
jqueryf#websharper

WebSharper : How to use the .On event handler


I'm trying to use JQuery provide by WebSharper to catch the following event : selectstart.

So I write the following code :

JQuery.Of(".editorArea").On("selectstart", fun x ->
    (
        JavaScript.Log("test")
        true
    )
)

The problem is this never print the test string in the console. And I don't know how to use x which have the obj type so I can't really access the event informations.


Solution

  • There is nothing wrong with your code unless you're binding the event to a textarea, input:password or input:text. In that case you need to listen to the "select" event instead of "selectstart" like in the example below (notice the event object's explicit downcast to Dom.Event in order to access its information):

    [<InlineAttribute "$elt.value.substring($elt.selectionStart, $elt.selectionEnd)">]
    let selectedText elt = X<string>
    
    let textareaSelection() =
        TextArea [Text "Select me"; Attr.Class "editorArea"]
        |>! OnAfterRender (fun _ ->
            JQuery.Of(".editorArea").On("select", fun x ->
                (As<Dom.Event> x).CurrentTarget
                |> selectedText
                |> JavaScript.Log
                true)     
            )