Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make button click listener event in Kotlin/JavaScript?

Inside IntellJ IDEA, I ve created a button in my HTML file with an id. What I'm trying to achieve is to change the header tag to "button clicked" using kotlin.

Upon searching the kolinlang.org website and others resources I have trouble finding simple reference for doing specific things I wonder if there a translated kotlin/javascript site where all of them is put together like this site for example: https://www.w3schools.com/js/default.asp

Thanks

like image 542
Black Boy Avatar asked Dec 19 '25 15:12

Black Boy


1 Answers

  1. Create a Kotlin/JS project in IntelliJ, named "JSProject"
  2. Create an index.html file including a button with ID "mybutton"
  3. Create a Kotlin file main.kt with the following content:
import org.w3c.dom.HTMLButtonElement
import kotlin.browser.document

fun main(args: Array<String>) {
    val button = document.getElementById("mybutton") as HTMLButtonElement
    button.addEventListener("click", {
        document.title = "button was clicked"
    })
}
  1. Import the Kotlin JS library and your code (JS compiled from Kotlin) in at the end of your HTML file:
       ...
       <script src="out/production/JSProject/lib/kotlin.js"></script>
       <script src="out/production/JSProject/JSProject.js"></script>
    </body>
    </html>
  1. Compile your Kotlin code to JS (menu: Build | Rebuild Project)

  2. Open the index.html file in a web browser and click on the button. "button was clicked" appears in the title.

like image 142
Andi Avatar answered Dec 22 '25 07:12

Andi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!