Kotlin js: strange behaviour in HTMLDivElement.onclick


#1

here is a working code that adds a “!” to the innerHTML of the

element after each click.
var list = document.getElementById("pannel") as HTMLDivElement
var contactPannel = document.createElement("div") as HTMLDivElement
contactPannel.innerHTML = "name"
contactPannel.onclick = {
    contactPannel.innerHTML = contactPannel.innerHTML + "!"
    var newRow = document.createElement("div") as HTMLDivElement // does not work when commented out
    list.appendChild(newRow) // does not work when commented out
}
list.appendChild(contactPannel)

the same code with only two lines commented out does not work

var list = document.getElementById("pannel") as HTMLDivElement
var contactPannel = document.createElement("div") as HTMLDivElement
contactPannel.innerHTML = "name"
contactPannel.onclick = {
    contactPannel.innerHTML = contactPannel.innerHTML + "!"
   // var newRow = document.createElement("div") as HTMLDivElement // does not work when commented out
   // list.appendChild(newRow) // does not work when commented out
}
list.appendChild(contactPannel)

for some stange reasons i get the error “Kotlin: Expeced a value of type dynamic” for the line where i try to add the “!” to the innerHTML. can anybody explain the meaning of that error message?


#2

type signature of lambda is not compatible with onclick. onclick declaration expecting dynamic, lambda with commented out values returns Unit. Quick hacky way to fix, add null on last line in lambda. Proper way - don’t use onclick :slight_smile:


#3

thanks!
i still dont understand at all why adding null at the end of the line solves the error of the line above, but anyway it works! :slight_smile:

and i also did not understand your “proper way”, how can i trigger onclick event without using onclick? do you mean i shoudl use the addEventListener("onclick … instead?


#4

adding null changes lambda return type. return keyword is not always needed. side effect of “almost everything is expression” in kotlin

onclick attribute is old way (pre IE6). main problem it is single attribute, to have two onclick’s on same node you have to implement some kind of “framework” yourself.


#5

Feel free to vote on the related issue https://youtrack.jetbrains.com/issue/KT-7612