JavaScript - enable on then off

I have an image of a light switch on my website. It launches a function (using onClick), which makes the entire wrapper div equal to opacity 0.2, which gives the effect of the light off.

Thus, the switch is pressed and the indicators are “off”, however, I cannot decide how to turn them on.

function lightSwitch()
{
    document.getElementById("switchoff").style.opacity = '0.2';
}

I am very new to JavaScript, so I'm sure the solution is simple.

+3
source share
5 answers
function lightSwitch()
{
    var el = document.getElementById("switchoff"),
        opacity = el.style.opacity;

    if(opacity == '0.2')
        el.style.opacity = '1';
    else
        el.style.opacity = '0.2';
}

note - this is not verified, the actual value may differ (".2" or "0.2") - you need to check "

+5
source

If I understand your question correctly, you want to disable it after a while.

, setTimeout - :

function lightSwitch()
{
    document.getElementById("switchoff").style.opacity = '0.2';
    setTimeout(...function to turn it off...,5000); // 5000 mseconds
}

: JS timing

+2

CSS "lightsOut" / switchoff.

function toggleClass( element, className ) {
    element.classList.toggle( className );
}

. classList Internet Explorer, Eli Grey polyfill . , . , id switchoff, :

toggleClass( document.getElementById("switchOff"), 'lightsOut' );
+2

div CSS "on", "off", toggleClass JQuery.

$(document).ready(function () {

        $(".switchClass").click(function () {
            $(this).toggleClass("off");
            return false;
        });
     });

CSS

div.switchClass{
//Insert your own look and feel
}

div.off.switchClass{
//Same style as div.switchClass except change the opacity
opacity: 0.2;
}
+2

- .

 function lightSwitch() {     

  var lightSwitch = document.getElementById("switchoff");

  if(lightSwitch.style.opacity != "0.2") //If the div is not 'off'
  {
     lightSwitch.style.opacity = '0.2'; //switch it 'off'
  }
  else
  {
     lightSwitch.style.opacity = '1.0'; // else switch it back 'on'      
  }
} 
+1

All Articles