Frage

I'm trying to change the text colour of 2 classes depending on whether the query mobile flip switch is on or off. I was under the impression the flip switch was just a checkbox with the on state being checked and off state being unchecked. My javascript experience is very minimal. Anyone know how I can fix this?

CLASSES

<div class="text-left">Make me blue when switch is off and grey when on </div>
<div class="text-right">Make me blue when switched is on and grey when off</div>

SWITCH

<form>
<input type="checkbox" data-role="flipswitch" name="flip-checkbox-4" id="flip-checkbox-4" data-wrapper-class="custom-size-flipswitch">
</form>

JAVASCRIPT

<script type="text/javascript">
if($("#flip-checkbox-4").is(":checked")) {
    $(".text-left").css("color", "grey");
    $(".text-right").css("color", "blue");
} else {
    $(".text-left").css("color", "blue");
    $(".text-right").css("color", "grey")
}
</script>
War es hilfreich?

Lösung

You need to wrap it inside of an event; specifically, a change() event, to listen out for when the checked property of the input is changed:

$("#flip-checkbox-4").change(function(){
  if($("#flip-checkbox-4").is(":checked")) {
     $(".text-left").css("color", "grey");
     $(".text-right").css("color", "blue");
  } else {
     $(".text-left").css("color", "blue");
     $(".text-right").css("color", "grey")
  }
});

jsFiddle here.

A shorter way to do this:

$("#flip-checkbox-4").change(function(){
   $(".text-left").css("color", this.checked ? "grey" : "blue");
   $(".text-right").css("color", this.checked ? "blue" : "grey");
});

jsFiddle here.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top