Accepted answer

In Scala.js, scala.FunctionNs can be converted implicitly to js.FunctionNs and back, so you basically don't need to do anything: just pass in a lambda to the JavaScript call. There is an example of this in Step 5 of the the tutorial, under "Setup UI in Scala.js". For your code, it would look like this:

jQuery(dom.document).ready { () =>
  val svgContainer = ...

You can find more information on this in the calling JavaScript guide.


Here is the translation of your entire JavaScript snippet:

import scala.scalajs.js
import org.scalajs.dom           // see
import org.scalajs.jquery.jQuery // see

object ScalaJSExample extends js.JSApp {
  val d3 = // assuming you don't have static types for d3, here

  def main(): Unit = {
    jQuery(dom.document).ready { () =>
      val svgContainer ="body").append("svg")
          .attr("width", 1200)
          .attr("height", 1200)
          .attr("text-align", "center")

  def testFunction(svgContainer: js.Dynamic): Unit = {

As you can see:

  1. For libraries that have static types for Scala.js (e.g., DOM and jQuery), it is best to use these static types. Here is use ready(), dom.document and dom.alert in a statically typed fashion.
  2. When you don't have static types, you can use js.Dynamic to manipulate JavaScript values in a dynamically typed way, using the normal syntax (not strings)
  3. You define functions with def. It shouldn't matter to you whether they are compiled as JavaScript functions or not: just write your Scala code without thinking about it, the compiler will do its job.

Related Query

More Query from same tag