Home > database >  A button dynamic links to an image
A button dynamic links to an image

Time:10-10

I am trying to hide/show dynamically an image through JavaScript, but i can't figure out how to do that. I have the following:

let button = document.querySelector('#button');
let msg = document.querySelector('#image');

button.addEventListener('click', ()=>{
  msg.classList.toggle('show');
})
#button{
  width: 200px;
  text-align: center;
  padding: 10px;
  font-size: 30px;
  cursor: pointer;
  margin: auto;
 
}
.hide{
  visibility: hidden;
}
.show{
  visibility: visible;
}
<div id="image" class="hide">
    <img class="screenshot" width="238" height="222" src="https://picsum.photos/200" alt="screenshot"  />
</div>
<div id="button">
    Click!
</div>

I think that the src="https://picsum.photos/200" must be implemented in the JS page, not in the HTML page.

CodePudding user response:

 <div id="image" class="show">
  <img
    class="screenshot"
    width="238"
    height="222"
    src="https://picsum.photos/200"
    alt="screenshot"
  />
</div>

let button = document.querySelector("#button"); let msg = document.querySelector("#image");

  button.addEventListener("click", () => {
    // msg.classList.toggle("show");
    if(msg.className==="show"){
        msg.className= "hide"
    }else{
        msg.className= "show"

    }

  });

CodePudding user response:

If you want to change src you need to select the image. You can then get to the parent from there to change the class.

  • Don't use id="" if you want multiple things.

Is a bit unclear what you mean by dynamic, I'm presuming you mean having multiple buttons which show different images. If so then use a data attribute on the button, much like you would if it was a link.

let screenshot = document.querySelector('.screenshot')
let buttons = document.querySelectorAll('.button')

buttons.forEach(button => button.addEventListener('click', event => {
  screenshot.src = event.target.dataset.image

  screenshot.parentElement.className = 'show'
}))
.button {
  width: 200px;
  text-align: center;
  padding: 10px;
  font-size: 30px;
  cursor: pointer;
  margin: auto;
}

.hide {
  display: none;
}

.show {
  display: block;
}
<div class="hide">
  <img class="screenshot" width="300" height="200" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNcWg8AAc8BJpg2zxQAAAAASUVORK5CYII=" alt="screenshot" />
</div>

<div class="button" data-image="https://picsum.photos/id/1/300/200">
  Click! (1)
</div>

<div class="button" data-image="https://picsum.photos/id/2/300/200">
  Click! (2)
</div>

  • Related