-3

In CSS I have a div tag that is like a comment section, but I want it hidden until the user clicks on the comment image. How do I make the div display when the user clicks on it using JavaScript?

HTML:

<div class = "comments">
   <img onclick = "commentBar()" src = "comment.png" />
</div>

CSS:

.comments{
   width: 200px;
   height: 200px;
   background-color: blue;
   display: none;
}

How do I make the div tag re-appear when I click on the image?

5
  • 1
    "How do I make the div tag re-appear when I click on the image?" - you don't, because you can't. The parent element is removed via display:none, so the image is gone as well. Can't click on what ain't there. Commented Apr 28, 2017 at 18:33
  • And How to make a DIV visible and invisible with JavaScript Commented Apr 28, 2017 at 18:33
  • CBroe is the voice of reason in this flood of downvotes and close requests. I'm going to post that idea as an answer. Commented Apr 28, 2017 at 18:38
  • @CBroe To be clear, the element isn't removed. It's just not rendered onto the browser viewport. The element is still part of the DOM. Commented Apr 28, 2017 at 18:50
  • @Rob I'm fully aware of that. But it is "removed" from being displayed, and being interacted with by the user in any way, and that includes all of its descendants. (With visibilitythat would be a different story.) I just didn't want to phrase it too technical, but rather "blunt" to point out the obvious error in reasoning. Commented Apr 28, 2017 at 19:02

1 Answer 1

2

When an element is hidden with display: none, its descendants are also hidden. You can't hide a parent and then selectively show some children. Thus the "comment image" won't show up for the user to be able to click it.

What you could do is have the toggle button outside of the div that gets hidden. Or move the comments to a sibling of the image and hide that instead of the parent:

<div class="comments">
  <img onclick="..." ...>
  <div class="the-actual-comments">
    ...
  </div>
</div>

with

.comments {
  /* no display: none */
}
.the-actual-comments {
  display: none;
}

As for what to put in the onclick, I'm guessing you know how get the .the-actual-comments element and set its style.display to, say, 'block'.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.