How to hide an image using JavaScript.

This is a beginner’s tutorial on how to hide an image using JavaScript. To do this, you can either use regular JavaScript or the jQuery library. In this guide, I will show you how to use both.

Hiding an image using regular JavaScript.

To hide an image using “vanilla” JavaScript, you can simply modify its display value like so:

In the snippet above, we have an image element with the ID “my_image”. As a result, we can simply access that image using the getElementById() method and then change the display value to “none”. By setting the display value to “none”, we are essentially hiding the image from view.

Showing the image again.

Similarly, we can also re-display the image again:

Note that we use “inline” because that is the default display value for images. However, you can also set it to “block” if needs be.

Hiding an image using the jQuery library.

If you are already using the jQuery library in your project, then you can simply use the hide() method like so:

This will immediately hide the image from view.

The jQuery library also allows you to specify how quickly the image should be hidden. By default, it will be instant. However, you can also ease it out more slowly:

If you run the code above, you will see that the image is not hidden straight away. Instead, it is faded out.

Showing the image again using jQuery.

To show the image again, you can use the show() method:

This “un-hides” the image.

Hide an image after it is clicked.

If you want to hide an image after it has been clicked, you can use an event handler:

Here, we attached an inline “onclick” event handler to our image element. As a result, the function hide_image will be called as soon as a user clicks on the image. Inside our hide_image function, we set the display value to “none” and hide the image.

Facebook Comments