0

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 Answers 2

2

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 }
Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunatly, that does not seem to work. I tried writing onclick := { () => println("HELLO WORLD!") } but now I don't get any output. I noticed that it works with onchange := { () => println("HELLO WORLD!") } but then I will need a small work-around to distinguish if the user pressed the button or if it was changed by the API, so I would definetly prefer to use onclick.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.