The display property exchange does not work with if em js

Asked

Viewed 62 times

0

I’m a beginner in javascript, I can’t figure out the right syntax for coding to work. Note: I am trying to make the image toggle every click.

HTML)

    <label id='a'>
        <img class='cadeira' src='./img/cadeira.png'/>
        <img class='cadeira2' src='./img/cadeira2.png'/>
    </label>

JS)

function toggleImage(){
        const elChildren = document.getElementById("a").children;
        const img2 = elChildren[1];

            if(img2.style.display=="none"){
                img2.style.display="block";
                console.log("trocou");
            }
            else{
                img2.style.display="none";
                console.log("não trocou");
            }
    }
    function eventos(){
        const cadeira=document.getElementById("a");

        cadeira.addEventListener("click",toggleImage);

    }
    window.addEventListener("load",eventos);

My console.log eventually returns to "not changed".

If anyone can help me please, I really need that code for a project very soon. Thank you so much already.

  • Has there been any response?

  • It worked obg, and I got enough base, now I’m trying a way with several Labels kkkkk.

4 answers

1


Isa Bella, I tried to make as few changes as possible to your code, to make it easier for you. Take a look if this is what you wanted.
I added CSS to leave any images (off the first) hidden.
With Js, then, just change the position of the images in the DOM, doing a literal "dance of the chairs" (sorry, I couldn’t resist :) )

PS.: I used Defer in the script that calls javascript, so I didn’t need the eventListener load (because the page is already loaded) https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script

//Obtém os objetos label e a coleção de cadeiras no label
let label = document.getElementById('a');
let cadeiras = document.querySelectorAll('#a img');

//Adiciona handler para click no label
label.addEventListener('click', toggleImage);

function toggleImage(){
    //troca posição das cadeiras no DOM
    label.insertBefore(cadeiras[1], cadeiras[0]);
    //avisa no console
    console.log('trocadas as cadeiras');
    //atualiza o objeto cadeiras para refletir a troca
    cadeiras = document.querySelectorAll('#a img');
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="index.js" defer></script>
    <style>
        img{
            height: 300px;
        }
        #a{
            background-color: aqua;
        }
        #a img{
            display: none;
        }
        #a img:first-child{
            display: block;
        }
    </style>
    <title>Alternance</title>
</head>
<body>
    <label id='a'>
        <img class='cadeira' src='https://cdn.shopify.com/s/files/1/1640/2231/files/turntable_2020_OM_pu_stealth_2-min.jpg?v=2079812668809504478'/>
        <img class='cadeira2' src='https://officedepot.scene7.com/is/image/officedepot/7377876_p_realspace_tresswell_bonded_leather_high_back_chair?$OD%2DLarge$&wid=450&hei=450'/>
    </label>
</body>
</html>

  • Hi Paul, thank you so much for the code, clarified my thoughts. I tried to use the same reasoning for several Abels, but unfortunately it only works on the last label. I wanted to pass the code here so you can analyze but the line limit and the formatting of the comment prevent me. You would have some hint to help me?

  • You can leave Paulo, I managed to develop the code, but thank you very much kkkkk

1

By default, an image is not an element of block (block), is an element of line (inline), so don’t use .style.display = "block"; instead use .style.display = "inline" to display the image.

To switch between the two images, one of them has to be hidden by the CSS, so when you click one it will hide it and show the other and vice versa.

You can do it this way:

function toggleImage(){
   const elChildren = document.getElementById("a").children;
   const img1 = elChildren[0]; // primeira imagem
   const img2 = elChildren[1]; // segunda imagem

   if(img2.style.display=="none" || !img2.style.display){
      img1.style.display="none";
      img2.style.display="inline";
      //console.log("trocou");
   }
   else{
      img1.style.display="inline";
      img2.style.display="none";
      //console.log("não trocou");
   }
}

function eventos(){
   const cadeira=document.getElementById("a");
   cadeira.addEventListener("click",toggleImage);
}
window.addEventListener("load",eventos);
#a img{
   width: 100px;
   height: 100px;
}

/*ESCONDE A SEGUNDA IMAGEM*/
.cadeira2{
   display: none;
}
<label id='a'>
   <img class='cadeira' src='https://www.cleverfiles.com/howto/wp-content/uploads/2016/08/mini.jpg'/>
   <img class='cadeira2' src='https://tinyjpg.com/images/social/website.jpg'/>
</label>

1

Your logic is not correct, so I decided to write a minimal example, where:

  • I start images where only the first one will be visible.
  • By clicking on the image check if it is already the last and if it is not passed the visibility to another and so on and if it is the last turn to first.

let iniFoto = -1;
function toggleImage() {
  const elChildren = document.getElementById("a").children;   
  if (iniFoto + 1 === elChildren.length) {
    elChildren[iniFoto].style.display = 'none';
    iniFoto = 0;
    elChildren[iniFoto].style.display = 'block';    
  } else {
    elChildren[iniFoto].style.display = 'none';
    iniFoto++;
    elChildren[iniFoto].style.display = 'block';  
  }  
}

function eventos() {
  const cadeira = document.getElementById("a");
  cadeira.addEventListener("click", toggleImage);
}

function initImage() {
  const elChildren = document.getElementById("a").children; 
  iniFoto ++;
  for (i = 0; i < elChildren.length; i++) {
    if (i === iniFoto) {
      elChildren[i].style.display = 'block';
    } else {
      elChildren[i].style.display = 'none';
    }
  }
}
window.addEventListener("load", eventos);
initImage();
<label id="a">
   <img class="cadeira" src="https://fakeimg.pl/100/?text=1"/>
   <img class="cadeira" src="https://fakeimg.pl/100/?text=2"/>
   <img class="cadeira" src="https://fakeimg.pl/100/?text=3"/>
   <img class="cadeira" src="https://fakeimg.pl/100/?text=4"/>
   <img class="cadeira" src="https://fakeimg.pl/100/?text=5"/>
</label>

  • Virgilio, I went to run his code here and it worked '-' What witchcraft is that kkk ?

  • If you speak here in my answer ? this has long been a visual resource for Html, Javascript and Css.

  • No, I’m telling you the author’s code. His code works perfectly on mine but it doesn’t work on his or her apparently.

  • Guy the code doesn’t work I tried @Jeanextreme002

  • Oh leave it alone, I’ve got the question wrong. You’re right.

-1

Change your block if by just this line:

img2.style.display = img2.style.display == 'none' ? 'block': 'none';

Browser other questions tagged

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