Using bootstraptoggle's onclick event in a scala-js application

448 Views Asked by At

In my scala-js application I want to use the bootstraptoggle library to create a nice looking switch button.

So far I am creating the toggle button by a method looking somewhat like this:

import scalatags.JsDom
import scalatags.JsDom.all._
// ...


def createToggleButton(): JsDom.TypedTag[Input] = {
  def onClick = println("HELLO WORLD!")
  input(id := "myToggle",
        attr("data-toggle") := "toggle",
        `type` := "checkbox",
        onclick := onClick,
        attr("data-on") := "ON",
        attr("data-off") := "OFF",
        attr("data-onstyle") := "success",
        attr("data-width") := "85",
        attr("data-height") := "26")
}

When rendering this and adding it to my DOM it looks like this:

toggle off toggle on

So far everything is working. The peculiar thing is this however: When rendering the page ('F5') my console (Chrome - 'F12') shows one 'HELLO WORLD!' output right from the start. After that, the onclick event does not seem to fire anymore.

Does anyone know how to fix this?

2

There are 2 best solutions below

0
Florian Baierl On BEST ANSWER

Since I wasn't able to get the bootstrap-toggle to work, I decided to make my own. So, here is my solution: ToggleSwitchWithLabels.scala

1
sjrd On

You should give a function of the form () => action() to the attribute onclick. Currently you're evaluating the def onClick once, and storing the result of that function call (which is the () value) in the onclick attribute. Instead you should write

onclick := { () => onClick }