If I’m understanding correctly, this should be what you are looking for.
const showImage = () => {
document.getElementById("first").classList.toggle('hidden');
}
.hidden {
display: none;
}
<button onClick="showImage()">Button</button>
<div id="first" style="height:400px; width:400px;" class="hidden">
<p>Som text</p>
<img src="https://placekitten.com/400/400" />
</div>
There is a semantic HTML element called <figure>
that helps you to combine images with captions which might be useful.
In this example I’ve
-
Removed your inline JS, cached the main elements in the JS, and used addEventListener
to add a click listener to the button.
-
Used a CSS class (.show
) that can be toggled on/off (flex
/none
) using the element’s classList. I’ve used flex-box here to make aligning elements easier.
// Cache the elements
const figure = document.querySelector('figure');
const button = document.querySelector('button');
// Add a listener to the button
button.addEventListener('click', handleClick);
// When the button is clicked toggle
// the show class on the figure
function handleClick() {
figure.classList.toggle('show');
}
figure { display: none; margin-top: 1em; width: fit-content;}
img { border-radius: 5px; }
figcaption { margin-top: 0.25em; }
.show { display: flex; flex-direction: column; justify-content: center; align-items: center; }
<button type="button">Show example</button>
<figure>
<img src="https://placekitten.com/200/200" />
<figcaption>This is a lovely kitten.</figcaption>
</figure>
I want to create a button on my HTML page that reveals some images (and text) when a button is pressed. I want both to be revealed with one click and then hidden when the button is clicked again. I tried making a button that can be seen in my code that reveals an image but can’t seem to figure out to have it reveal text as well.
const showImage = () => {
document.getElementById("first").style.display = 'block';
}
<button onClick="showImage()">Button</button>
<div id="first" style="height:400px; width:400px; display:none;">
<img src="https://placekitten.com/400/400" />
</div>
Text can be inside a div just like an image can—what specific issue are you having?