Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 628
Sean Zulu Avatar asked Mar 01 '26 01:03

Sean Zulu


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

like image 97
Alex Avatar answered Mar 03 '26 16:03

Alex


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

like image 38
SlavaNov Avatar answered Mar 03 '26 14:03

SlavaNov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!