The Basics – A Simple Project
We also need to add the Kotlin standard library to the project. Clicking on the Create button we’ll be prompted with the location where we want these files copied. By default it copies is to a folder named script. And we’ll get to this later on as it’s important.
The resulting structure of the project should be
The project has two files that are added:
- The lib folder contains the header files, as a jar file, which are used during development.
- The script folder contains a single kotlin.js which is the Kotlin runtime library. This is used in production.
Setting up a workflow
During development we need to have an up to date version of these files so ideally we’d like to have these located in our web/js/app folder. We can do this in many ways, either using IntelliJ IDEA artifacts or Maven/Gradle. In our case we’re just going to use an artifact. We can set one up to copy the corresponding files to the desired output location and additional also copy the kotlin.js file that was originally copied to the script folder to the same location*.
*This is a one-time operation so a better alternative is to define the output location of this file directly to our required output folder when setting up the project. We have done it this way to explain things step by step.
Interacting with DOM Elements
Now that we have the project layout ready, let’s start writing some code. The most basic thing we can do is manipulate some DOM elements. We can create a simple HTML page (named index.html) and place it under the web folder
The idea is to now update the value of the input field using Kotlin. For that we can create a new file called main.kt and place it under our src folder.
Kotlin provides a series of libraries targeted specifically at the web. In our case, since we want to manipulate the DOM, we can import the js.dom.html to access the documentvariable. The resulting code would be
The standard library already provides support for DOM manipulation, HTML 5 features such as Canvas and Local Storage, as well as wrappers for common libraries such as jQuery. We will be adding more as we go along, and we’ll cover some of them in future posts.
Running the code
Now that we have the code compiled, we need to actually run it. For this we have to reference both the kotlin.js as well as the generated (basic.js) file from our index.html page.
The code corresponding to the main function will automatically be called when the page is loaded.
Once we load our index.html page, we should see the result.
This is placed inside the same module as the application and we can call it referencing it by the Kotlin module name*
*This API is not final and will most likely change in the future, and probably will be much more compact.