What is event type in mouse listeners?


Hi, I’m trying to use kotlinx.html-js builders and I can’t figure out how to work with event passed to event handler. Example

onMouseDownFunction = { e ->
    // Got "uncaught exception: ClassCastException: Illegal cast" here
    val mouseDownEvent = e as org.w3c.dom.events.MouseEvent 

I can use org.w3c.dom.events.MouseEventInit class instead but it does not have all MouseEvent properties described in documentation. In particular I’m nterested in pageX and pageY properties.

I can achieve what I want by this:

val pageX = mouseDownEvent.asDynamic().pageX as Int

But it’s kind of ugly. Is this the only way to go or I’m missing something?


I can’t reproduce. The following code works for me (with Kotlin 1.1.4):

import kotlinx.html.dom.create
import kotlinx.html.js.div
import kotlinx.html.js.onMouseDownFunction
import org.w3c.dom.events.MouseEvent
import kotlin.browser.document
import kotlin.browser.window

fun main(args: Array<String>) {
    window.onload = {
        document.body!!.append(document.create.div {
            +"Hello, world!"
            onMouseDownFunction = {
                println(it as MouseEvent)

A small hint: you can use similar trick with ::class.js.name to figure out what actual type is there. Also, you can use debugger to see what happens and where from you get to the event handler.


@Alexey.Andreev, thanks for the tip. I’m using React and it turned out that the actual event passed to React component event listeners has type of SyntheticEvent instead of DOMEvent.
For future readers of this topic: when using React you can either stick with React SynteticEvent or if you still want to use DOMEvent you can do something like this:

onMouseDownFunction = { syntheticEvent ->
      val domMouseDownEvent = syntheticEvent.asDynamic().nativeEvent as MouseEvent


Hi @mikhalchenko.alexander I’ve just spent two hours trying to figure it out why cast to KeyboardEvent doesn’t work :frowning: so very much thanks for your answer !

However, I’m wondering what do you mean by

but I’m not sure hw could I use it if I don’t have any interface headers for React’s SyntheticEvent ? The only way I see is through asDynamic() which seems to be a bit ugly :confused:


@macszur Unfortunately I don’t have an example code but you can create wrapper for React SynteticEvent yourself by using external modifier. See documentation. After you create a wrapper for SynteticEvent and declare required methods and fields in it you can cast actual event to your wrapper and use it as normal Kotlin object. Hope that’s clear :slight_smile:


Thanks for your help ! With documentation and little help of this repository https://github.com/danfma/kodando (where I’ve found some bindings for SyntheticEvent and related events) I was able to write my own wrappers and they seems to be working quite fine :wink: