Categories
JavaScript Answers

How to show or hide an image with JavaScript?

Spread the love

Sometimes, we want to show or hide an image with JavaScript.

In this article, we’ll look at how to show or hide an image with JavaScript.

How to show or hide an image with JavaScript?

To show or hide an image with JavaScript, we can set the style.visibility property of the img element.

For instance, we write:

<button id='showBtn'>show image</button>
<button id='hideBtn'>hide image</button>
<img src="https://picsum.photos/200/300">

to add buttons and img elements.

Then we write:

const showBtn = document.getElementById('showBtn')
const hideBtn = document.getElementById('hideBtn')
const img = document.querySelector('img');

showBtn.onclick = () => {
  img.style.visibility = 'visible';
}

hideBtn.onclick = () => {
  img.style.visibility = 'hidden';
}

We select the elements with getElementById and querySelector.

Then we set the onclick property of the buttons to functions that sets the img.style.visibility property.

'visible' makes the img element visible and 'hidden' makes the img element hidden.

Conclusion

To show or hide an image with JavaScript, we can set the style.visibility property of the img element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *