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:

<img src="image.png" id="my_image">

<script>
    //Hiding the image using regular JavaScript.
    document.getElementById('my_image').style.display = 'none';
</script>

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:

//Show the image again by setting the display back to "inline"
document.getElementById('my_image').style.display = 'inline';

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:

<img src="image.png" id="my_image">

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
    //Hide the image using jQuery's hide() method.
    $('#my_image').hide();
</script>

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:

//Hiding the image slowly
$('#my_image').hide('slow');

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

Showing the image again using jQuery.

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

//Show the image using jQuery
$('#my_image').show();

This “un-hides” the image, so to speak.

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:

<img src="image.png" id="my_image" onclick="hide_image('my_image');">

<script>
    //Function that is called when the user clicks on the image
    function hide_image(id){
        document.getElementById(id).style.display = 'none';
    }
</script>

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.