Modifying a tag in an event handler?

152 views
Skip to first unread message

Ben Hutchison

unread,
Nov 6, 2014, 11:18:30 PM11/6/14
to scal...@googlegroups.com
I'm really unsure how Scalatags handles /modification/ of tags after initial construction. 

For instance, if I have constructed a span() element, added it to a webpage DOM, and in an event handler want to modify the content of it to show a message, how do I do that?

-Ben

Haoyi Li

unread,
Nov 6, 2014, 11:24:19 PM11/6/14
to Ben Hutchison, scal...@googlegroups.com
Would something like this work for you?
package webpage

import org.scalajs.dom
import scala.scalajs.js.annotation.JSExport
import scalatags.JsDom.all._

@JSExport
object Inputs extends{
  @JSExport
  def main(target: dom.HTMLDivElement) = {
    val box = input(
      `type`:="text",
      placeholder:="Type here!"
    ).render

    val output = span.render

    box.onkeyup = (e: dom.Event) => {
      output.textContent =
        box.value.toUpperCase
    }

    target.appendChild(
      div(
        h1("Capital Box!"),
        p(
          "Type here and " +
          "have it capitalized!"
        ),
        div(box),
        div(output)
      ).render
    )
  }
}

You can of course wrap this sort of mutation in whatever API you want, e.g. this guy wraps it such that it can be used seamlessly with Scala.Rx.

I know the documentation of using Scalatags in the Javascript/JsDom environment is kinda sparse/missing. I'm working on fixing that, but for now just ask questions =)

--
You received this message because you are subscribed to the Google Groups "Scalatags" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scalatags+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Ben Hutchison

unread,
Nov 7, 2014, 8:41:56 PM11/7/14
to Haoyi Li, scal...@googlegroups.com
Yeah, that works, thanks!

I think the key realization for me is that the mutation is done on the actual DOM object, ie 'output.textContent', not on the pre-'render' scalatag.

It's unfortunate (and feels a bit inconsistent) that the scalatags DSL around building trees isn't available during modification. But has to be that way, I guess. 

-Ben

Haoyi Li

unread,
Nov 7, 2014, 8:45:52 PM11/7/14
to Ben Hutchison, scal...@googlegroups.com

It doesn't *have* to be that way. It is entirely possible to make the DSL work with post-rendered tags, someone just needs to do it :P

Reply all
Reply to author
Forward
0 new messages