3

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

Black Boy
  • 91
  • 2
  • 9
  • are you asking the solution for javscript?? cause kotlin cannot be used in doing so in a webpage – Anand Siddharth Nov 28 '17 at 20:04
  • @AnandSiddharth Kotlin/JS is a valid compilation target - it would work. – Salem Nov 28 '17 at 20:08
  • This might work out : In that html button set a onclick handler (as mentioned here https://kotlinlang.org/docs/reference/js-to-kotlin-interop.html) you can call a Kotlin function which then executes this javscript `document.getElementsByTagName('header').item(0).innerHTML = 'button clicked'`. (as mentioned here https://kotlinlang.org/docs/reference/js-interop.html) @1blustone Thanks for letting me know about this kotlin stuff and Please mention if I am wrong any where in this comment – Anand Siddharth Nov 28 '17 at 20:20
  • @AnandSiddharth Thanks for responding I tried a number things to get it work but can't seem to figured this out I created a gist of my code: https://gist.github.com/blackBoyCode/8aab3e8172b4c394f3e6da7b207dc002 – Black Boy Nov 30 '17 at 19:44

1 Answers1

5
  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.

Andi
  • 3,234
  • 4
  • 32
  • 37