summaryrefslogtreecommitdiff
path: root/examples/scala-js/examples/helloworld/HelloWorld.scala
blob: fd330608ff49dd0e30e0e172baaad9c21099886b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/* Scala.js example code
 * Public domain
 * @author  Sébastien Doeraene
 */

package helloworld

import scala.scalajs.js
import js.annotation.JSName

object HelloWorld extends js.JSApp {
  def main() {
    if (!(!js.Dynamic.global.document) &&
        !(!js.Dynamic.global.document.getElementById("playground"))) {
      sayHelloFromDOM()
      sayHelloFromTypedDOM()
      sayHelloFromJQuery()
      sayHelloFromTypedJQuery()
    } else {
      println("Hello world!")
    }
  }

  def sayHelloFromDOM() {
    val document = js.Dynamic.global.document
    val playground = document.getElementById("playground")

    val newP = document.createElement("p")
    newP.innerHTML = "Hello world! <i>-- DOM</i>"
    playground.appendChild(newP)
  }

  def sayHelloFromTypedDOM() {
    val document = window.document
    val playground = document.getElementById("playground")

    val newP = document.createElement("p")
    newP.innerHTML = "Hello world! <i>-- typed DOM</i>"
    playground.appendChild(newP)
  }

  def sayHelloFromJQuery() {
    // val $ is fine too, but not very recommended in Scala code
    val jQuery = js.Dynamic.global.jQuery
    val newP = jQuery("<p>").html("Hello world! <i>-- jQuery</i>")
    newP.appendTo(jQuery("#playground"))
  }

  def sayHelloFromTypedJQuery() {
    val jQuery = helloworld.JQuery
    val newP = jQuery("<p>").html("Hello world! <i>-- typed jQuery</i>")
    newP.appendTo(jQuery("#playground"))
  }
}

object window extends js.GlobalScope {
  val document: DOMDocument = js.native

  def alert(msg: String): Unit = js.native
}

trait DOMDocument extends js.Object {
  def getElementById(id: String): DOMElement = js.native
  def createElement(tag: String): DOMElement = js.native
}

trait DOMElement extends js.Object {
  var innerHTML: String = js.native

  def appendChild(child: DOMElement): Unit = js.native
}

@JSName("jQuery")
object JQuery extends js.Object {
  def apply(selector: String): JQuery = js.native
}

trait JQuery extends js.Object {
  def text(value: String): JQuery = js.native
  def text(): String = js.native

  def html(value: String): JQuery = js.native
  def html(): String = js.native

  def appendTo(parent: JQuery): JQuery = js.native
}