ArticleZip > Show Hide Image With Javascript

Show Hide Image With Javascript

JavaScript is a powerful tool that can enhance the user experience on websites by enabling interactive features. One common use case is to show and hide images dynamically based on user actions. In this article, we will explore how you can achieve this functionality in JavaScript.

To start, let's create a simple HTML file with an image element that we can manipulate using JavaScript. Here's an example code snippet to get you started:

Html

<title>Show and Hide Image with JavaScript</title>
    
        img {
            display: none; /* Hide the image by default */
        }
    



    <button>Show/Hide Image</button>
    <img id="myImage" src="image.jpg" alt="Sample Image">
    
    
        function toggleImage() {
            var img = document.getElementById('myImage');

            if (img.style.display === 'none') {
                img.style.display = 'block'; // Show the image
            } else {
                img.style.display = 'none'; // Hide the image
            }
        }

In the provided code snippet, we have an image tag with an `id` attribute set to "myImage." Initially, the image is hidden using CSS with the `display: none` property. Next, we have a button element with an `onclick` attribute that calls the `toggleImage` function when clicked.

The `toggleImage` function utilizes the `getElementById` method to select the image element by its ID. It then checks the current display style of the image. If the image is hidden (`display` is set to `'none'`), the function changes the display style to `'block'`, making the image visible. Conversely, if the image is visible, the function sets the display style back to `'none'` to hide it.

By clicking the "Show/Hide Image" button, you can toggle the visibility of the image on the webpage. This simple JavaScript functionality can be expanded and customized based on your specific requirements and design needs.

In conclusion, using JavaScript to show and hide images dynamically adds interactivity to your web pages and can create a more engaging user experience. Experiment with the provided code snippet and tailor it to suit your project's needs. Have fun incorporating this feature into your web development projects!

×