0

my objective is to have an image hidden until a button is pressed to then show the previously hidden image.

Right now I have an image in html with an Id of "yellowrose" that is hidden with this code:

    <div id="yellowrose"><img src="https://i.imgur.com/ppfhZa6.jpg" style="visibility:hidden"></div>

In JS I have several things happening with the buttonx.onclick, but I can't seem to make the image visible. Here's my JS code:

    var content = document.getElementById("content");
var buttonx = document.getElementById("show-more");
let yellowrose = document.getElementById("yellowrose");


window.onload = function(){
    
buttonx.onclick = function () {
    document.getElementById("yellowrose").style.visibility="visible";
          if(content.className == "open") {
              //shrink the box
              content.className = "";
              buttonx.innerHTML = "Continue to the Sunlit Pavillion?";
          } else{
              //expand the box
              content.className = "open";
              buttonx.innerHTML = "As you wander through the garden grounds you notice a striking Yellow Rose";
              
          }

          }
        }

Do you have any suggestions on how I can make the "yellowrose" image visible through the buttonx.onclick function? Thank you.

1
  • 1
    Please move your style="visibility:hidden" in the img tag to your <div id="yellowrose"> as your JavaScript is targeted to yellowrose which is div tag not img tag.
    – Tommy Tom
    Commented Jul 23, 2021 at 1:55

1 Answer 1

0

An id cannot contain a space.

As per MDN:

id's value must not contain whitespace (spaces, tabs etc.). Browsers treat non-conforming IDs that contain whitespace as if the whitespace is part of the ID. In contrast to the class attribute, which allows space-separated values, elements can only have one single ID value.

Additionally, you are setting the visibility of #yellowrose, the container of the image, and not the image itself. To solve this, simply get the firstChild property:

var content = document.getElementById("content");
var buttonx = document.getElementById("showmore");
let yellowrose = document.getElementById("yellowrose");


window.onload = function() {

  buttonx.onclick = function() {
    document.getElementById("yellowrose").firstChild.style.visibility = "visible";
    if (content.className == "open") {
      //shrink the box
      content.className = "";
      buttonx.innerHTML = "Continue to the Sunlit Pavillion?";
    } else {
      //expand the box
      content.className = "open";
      buttonx.innerHTML = "As you wander through the garden grounds you notice a striking Yellow Rose";

    }

  }
}
.open{
  visibility:visible !important;
}
<div id="yellowrose"><img src="https://i.imgur.com/ppfhZa6.jpg" style="visibility:hidden"></div>
<button id="showmore">Show More</button>
<div id="content">
content
</div>

Not the answer you're looking for? Browse other questions tagged or ask your own question.