Sean Zulu
Sean Zulu

Reputation: 149

JavaScript - Turning a switch on, then off

I have a light switch image on my website. It triggers a function (using onClick) which makes the whole wrapper div have an opacity of 0.2 giving the effect of lights being off.

So the switch is clicked and the lights are "off", however I cannot work out how to turn them back on.

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

I am very new to JavaScript so I am confident the solution is simple.

Upvotes: 3

Views: 811

Answers (5)

broguyman
broguyman

Reputation: 1426

You could give the wrapper div a class in CSS for "on" and another for "off" then toggleClass with 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;
}

Upvotes: 2

Sampson
Sampson

Reputation: 268424

The better approach would be to create a CSS class called 'lightsOut', and add/remove this to your switchoff element.

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

Note, classList is not implemented in Internet Explorer, so you would need to reference Eli Grey's polyfill for this. In order to use this function, you pass it an element and a class name. So to use it again an element with the id switchOff, we could do the following:

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

Upvotes: 2

SlavaNov
SlavaNov

Reputation: 2485

If I understood your question right, you want to turn it off after some time.

So you should use setTimeout something like this:

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

More info: JS timing

Upvotes: 2

Mark Walters
Mark Walters

Reputation: 12390

Something like this should work.

 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'      
  }
} 

Upvotes: 1

Alex
Alex

Reputation: 35407

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 tested, the actual value may differ (".2" or "0.2") - you need to test"

Upvotes: 5

Related Questions