Make lamp light on and off

Asked

Viewed 3,268 times

2

I’m studying javascript and I did an exercise where I have a picture of a light bulb out where when I click it changes the light bulb putting on, as if I were lighting a light bulb, but I am in doubt I do not know how to change the image to make the effect of erasing again. Follow the code below as I implemented.

<script>
    function ligar(){
        document.getElementById('lamp').src = "images/lampada-on.jpg";
    }
</script>

  • Please mark one of the answers with . Do not leave the question open. Check the answer that solved your problem.

5 answers

6

You can do it this way

function ligarDesliga(){

    var imagem = document.getElementById('lamp').src;
    var imagem_ligado = 'https://www.w3schools.com/js/pic_bulbon.gif';
    var imagem_desligado = 'https://www.w3schools.com/js/pic_bulboff.gif';
    
    if(imagem == imagem_ligado){
    	document.getElementById('lamp').src = imagem_desligado;
    }else{
    	document.getElementById('lamp').src = imagem_ligado;
    }
}
document.getElementById("lamp").addEventListener("click", ligarDesliga);
#lamp{
  cursor: pointer;
  cursor: hand;
}
<img id="lamp" src="https://www.w3schools.com/js/pic_bulboff.gif">

HTML

<img id="lamp" src="images/lampada-off.jpg">

Javascript

This is just to leave the cursor in the same way as a "little hand" link, so the user understands that it is possible to click on that image.

#lamp{
  cursor: pointer;
  cursor: hand;
}

Javascript

function ligarDesliga(){

    var imagem = document.getElementById('lamp').src;
    var imagem_ligado = 'images/lampada-on.jpg';
    var imagem_desligado = 'images/lampada-off.jpg';

    if(imagem == imagem_ligado){
        document.getElementById('lamp').src = imagem_desligado;
    }else{
        document.getElementById('lamp').src = imagem_ligado;
    }
}
document.getElementById("lamp").addEventListener("click", ligarDesliga);

I created an event click for the id "Lamp" and the function "turn on Sliga" checks which image is present in the tag and changes it, making the effect on and off.

Update

Another example of W3 Tryjs Intro Lightbuld

  • 1

    I think it looks better by how snippet than external reference...

  • Taking advantage, the sockets of the lamps switched off and on are distinct xD It may call me crazy, but it caught my attention immediately when I saw

  • 1

    Now the lamp is ugly, but it’s the same.

  • 1

    I put in the snippet itself !!!

  • 2

    Thanks @Virgilionovic, I didn’t know that this feature was called Snippet, when "Jefferson" told me that, I googled the meaning here and understood that it was something else.

  • I did exactly as you did there in this code, but when changing the address of the images to my ones in the directory it shows an error in the console and does not work. I click to light the lamp and it lights up, but when I click again to erase, does not work and an error appears.

  • What is the error that appears?

Show 2 more comments

3

Let`s Go!

$('.cube-switch .switch').click(function() {
    if ($('.cube-switch').hasClass('active')) {
        $('.cube-switch').removeClass('active');
        $('#light-bulb2').css({'opacity': '0'});
    } else {
        $('.cube-switch').addClass('active');
        $('#light-bulb2').css({'opacity': '1'});
    }
});
body {
  background: rgb(70, 72, 75);
}

/* SWITCH */
.cube-switch {
    border-radius:10px;
    border:1px solid rgba(0,0,0,0.4);
    box-shadow: 0 0 8px rgba(0,0,0,0.6), inset 0 100px 50px rgba(255,255,255,0.1);
    /* Prevents clics on the back */
    cursor:default;    
    display: block;
    height: 100px;
    position: relative;
    margin: 5% 0px 0px 10%;
    overflow:hidden;
    /* Prevents clics on the back */
    pointer-events:none;
    width: 100px;
    white-space: nowrap;
    background:#333;
}

/* The switch */
.cube-switch .switch {
    border:1px solid rgba(0,0,0,0.6);
    border-radius:0.7em;
    box-shadow:
    inset 0 1px 0 rgba(255,255,255,0.3),
    inset 0 -7px 0 rgba(0,0,0,0.2),
    inset 0 50px 10px rgba(0,0,0,0.2),
    0 1px 0 rgba(255,255,255,0.2);
    display:block;
    width: 60px;
    height: 60px;
    margin-left:-30px;
    margin-top:-30px;
    position:absolute;
    top: 50%;
    left: 50%;
    width: 60px;
 
    background:#666;
    transition: all 0.2s ease-out;

    /* Allows click */
    cursor:pointer;
    pointer-events:auto;
}

/* SWITCH Active State */
.cube-switch.active {
    /*background:#222;
    box-shadow:
    0 0 5px rgba(0,0,0,0.5),
    inset 0 50px 50px rgba(55,55,55,0.1);*/
}

.cube-switch.active .switch {
    background:#333;
    box-shadow:
    inset 0 6px 0 rgba(255,255,255,0.1),
    inset 0 7px 0 rgba(0,0,0,0.2),
    inset 0 -50px 10px rgba(0,0,0,0.1),
    0 1px 0 rgba(205,205,205,0.1);
}

.cube-switch.active:after,
.cube-switch.active:before {
    background:#333; 
    box-shadow:
    0 1px 0 rgba(255,255,255,0.1),
    inset 1px 2px 1px rgba(0,0,0,0.5),
    inset 3px 6px 2px rgba(200,200,200,0.1),
    inset -1px -2px 1px rgba(0,0,0,0.3);
}

.cube-switch.active .switch:after,
.cube-switch.active .switch:before {
    background:#222;
    border:none;
    margin-top:0;
    height:1px;
}

.cube-switch .switch-state {
    display: block;
    position: absolute;
    left: 40%;
    color: #FFF;

    font-size: .5em;
    text-align: center;
}

/* SWITCH On State */
.cube-switch .switch-state.on {
    bottom: 15%;
}

/* SWITCH Off State */
.cube-switch .switch-state.off {
    top: 15%;
}

#light-bulb2 {
width: 150px;
height: 150px;
background: url(https://lh4.googleusercontent.com/-katLGTSCm2Q/UJC0_N7XCrI/AAAAAAAABq0/6GxNfNW-Ra4/s300/lightbulb.png) no-repeat 0 0;
}

#light-bulb {
position: absolute;
width: 150px;
height: 150px;
top: 5%;
left: 40%;
background: url(https://lh4.googleusercontent.com/-katLGTSCm2Q/UJC0_N7XCrI/AAAAAAAABq0/6GxNfNW-Ra4/s300/lightbulb.png) no-repeat -150px 0;
cursor: move;
z-index: 800;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div href="" class="cube-switch">
        <span class="switch">
            <span class="switch-state off">Off</span>
            <span class="switch-state on">On</span>
        </span>
</div>
<div id="light-bulb" class="off ui-draggable" ><div id="light-bulb2" style="opacity: 0; "></div></div>

1

I believe this does what you need:

function liga_desliga(){

    const lamp = document.querySelector('#lamp');

    var src = ['lampada-on.jpg','lampada-off.jpg']
        .filter((value) => {
            var a = lamp.src.match(/\/(lampada-.+)/i)[1];
            return value != a;
        })[0];
    lamp.src = `images/${src}`;

}
  • Doing only with CSS is an option for you or how you are studying has to be with Script even?

  • I am studying javascript even pure and not jQuery

1

You can make a code similar to mine to change the lamp image.

<script>

    var atual_state = 'DESLIGADA';

    function mudaEstado() {
        atual_state === 'DESLIGADA' ? atual_state = 'LIGADA' : atual_state = 'DESLIGADA';
        return atual_state;
    }

    function ligaDesliga() {

        if (atual_state === 'DESLIGADA')
            document.getElementById('lampada').src = 'ligada.jpg';
        else
            document.getElementById('lampada').src = 'desligada.jpg';


        mudaEstado();

    }
</script>

<button onclick="ligaDesliga()"></button>
<img id="lampada" src="desligada.jpg">

1

A very simple and lean way to do this:

function ligarApagar(e){
   e.src = "images/lampada-"+( ~e.src.indexOf("-on") ? "off" : "on" )+".jpg";
   
   // daqui pra baixo é apenas exemplo para mostrar o texto
   // pode apagar
   document.querySelector("b").textContent = e.src;
   
}
<img height="100" id="lamp" src="images/lampada-on.jpg">
<b> https://stacksnippets.net/images/lampada-on.jpg </b>
<br>
<button type="button" id="controle" onclick="ligarApagar(document.getElementById('lamp'))">Ligar/Apagar</button>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.